Stream 流

非 Y 不嫁゛ 提交于 2019-12-03 06:38:52

1.stream.forEach() 与 collection.forEach()

虽然都是迭代方法,但执行结果完全不同。

如:

List<String> strl=Arrays.asList("aaa","bb","c","wwww","hh");
Stream.of(strl).forEach(System.out::println);------------------------------------------------------>①System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");strl.stream().forEach(System.out::println);-------------------------------------------------------->②System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");strl.forEach(System.out::println);----------------------------------------------------------------->③
输出结果如下:

[aaa, bb, c, hh, wwww]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
aaa
bb
c
hh
wwww
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
aaa
bb
c
hh
wwww

虽然idea提示 第②行可以简写为第三行的形式,但是

①②中的forEach()指向Stream接口,而③中的forEach()指向Iterable接口.

查看可知:

①中 Stream接口的of()方法返回的是一个仅有一个元素的Stream

Returns a sequential {@code Stream} containing a single element.
而②中.Stream()方法返回的是一个使用分割迭代器分割后的到的Stream
/** * Returns a sequential {@code Stream} with this collection as its source. * * <p>This method should be overridden when the {@link #spliterator()} * method cannot return a spliterator that is {@code IMMUTABLE}, * {@code CONCURRENT}, or <em>late-binding</em>. (See {@link #spliterator()} * for details.) * * @implSpec * The default implementation creates a sequential {@code Stream} from the * collection's {@code Spliterator}. * * @return a sequential {@code Stream} over the elements in this collection * @since 1.8 */


故①与②内部迭代得到的结果不一样。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!