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

最后修改: 2017年 1月 20日

1. Overview

1.概述

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

2.将Iterable转换为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 StreamSupport.stream() method and get a Stream from the given Iterable instance.

简单地说,你可以把它传递给StreamSupport.stream()方法,并从给定的Iterable实例中获得一个Stream

Let’s consider our Iterable instance:

让我们考虑一下我们的Iterable实例。

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:的方法。

StreamSupport.stream(iterable.spliterator(), false);

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

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

Now let’s test our implementation:

现在让我们测试一下我们的实现。

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

    Assert.assertNotNull(StreamSupport.stream(iterable.spliterator(), 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

3.执行操作

Let’s perform a simple stream operation:

让我们执行一个简单的流操作。

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

    List<String> result = StreamSupport.stream(iterable.spliterator(), false)
      .map(String::toUpperCase)
      .collect(Collectors.toList());

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

4. Conclusion

4.结论

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.

所有代码片段的实现都可以在Github项目中找到。