Iterable接口本省并没提供转换到stream方法。我们可以用StreamSupport.stream() 来实现。
Iterable<String> iterable = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");
转换方式
StreamSupport.stream(iterable.spliterator(), false);
编写测试代码
@Test public void givenIterable_whenConvertedToStream_thenNotNull() { Iterable<String> 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<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, IsCollectionContaining.hasItems("TESTING", "ITERABLE", "CONVERSION", "TO", "STREAM")); }
还是上我们的debug stream的插件神器(”Java Stream Debugger“),可以清晰看到中间操作的值。