Iterable接口本省并没提供转换到stream方法。我们可以用StreamSupport.stream() 来实现。
Iterable iterable
= Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");
转换方式
StreamSupport.stream(iterable.spliterator(), false);
编写测试代码
@Test
public void givenIterable_whenConvertedToStream_thenNotNull() {
Iterable iterable
= Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");
Assert.assertNotNull(StreamSupport.stream(iterable.spliterator(), false));
}
注意StreamSupport.stream的第二个参数决定是并行还是串行,如果设置为true则表示并行。
执行stream的操作
@Test
public void whenConvertedToList_thenCorrect() {
Iterable iterable
= Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");
List result = StreamSupport.stream(iterable.spliterator(), false)
.map(String::toUpperCase)
.collect(Collectors.toList());
assertThat(result, IsCollectionContaining.hasItems("TESTING", "ITERABLE", "CONVERSION", "TO", "STREAM"));
}
还是上我们的debug stream的插件神器(”Java Stream Debugger“),可以清晰看到中间操作的值。
英文原文:https://www.baeldung.com/java-iterable-to-stream
如果觉得本文对你有帮助,欢迎点赞评论,欢迎关注我,我将努力创作更多更好的文章。