Iterable to Stream in Java – Java中的Iterable到Stream

最后修改: 2017年 1月 20日

1. Overview


In this short tutorial, let’s convert a Java Iterable object into a Stream and perform some standard operations on it.

在这个简短的教程中,让我们把一个Java Iterable对象转换成Stream,并对它进行一些标准操作。

2. Converting Iterable to Stream


The Iterable interface is designed keeping generality in mind and does not provide any stream() method on its own.

Iterable接口的设计考虑到了通用性,并没有单独提供任何stream() 方法。

Simply put, you can pass it to method and get a Stream from the given Iterable instance.


Let’s consider our Iterable instance:


Iterable<String> iterable 
  = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");

And here’s how we can convert this Iterable instance into a Stream:

下面是我们如何将这个Iterable实例转换成Stream:的方法。, false);

Note that the second param in determines if the resulting Stream should be parallel or sequential. You should set it true, for a parallel Stream.

请注意,中的第二个参数决定了产生的Stream应该是并行的还是顺序的。你应该把它设置为 “true”,以获得一个并行的Stream

Now let’s test our implementation:


public void givenIterable_whenConvertedToStream_thenNotNull() {
    Iterable<String> iterable 
      = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");

    Assert.assertNotNull(, false));

Also, a quick side-note – streams are not reusable, while Iterable is; it also provides a spliterator() method, which returns a java.lang.Spliterator instance over the elements described by the given Iterable.

另外,一个简短的旁注–流是不可重用的,而Iterable是;它还提供了一个spliterator() 方法,它在给定的Iterable描述的元素上返回一个java.lang.Spliterator实例

3. Performing Stream Operation


Let’s perform a simple stream operation:


public void whenConvertedToList_thenCorrect() {
    Iterable<String> iterable 
      = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");

    List<String> result =, false)

      result, contains("TESTING", "ITERABLE", "CONVERSION", "TO", "STREAM"));

4. Conclusion


This simple tutorial shows how you can convert an Iterable instance into a Stream instance and perform standard operations on it, just like you would have done for any other Collection instance.

这个简单的教程展示了如何将Iterable 实例转换为Stream 实例并对其执行标准操作,就像你对其他Collection 实例所做的那样。

The implementation of all the code snippets can be found in the Github project.