首页 > 其他 > 详细

Stream 流

时间:2019-11-02 12:51:31      阅读:82      评论:0      收藏:0      [点我收藏+]

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
*/


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

Stream 流

原文:https://www.cnblogs.com/wanghuanyeah/p/11780988.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!