码迷,mamicode.com
首页 > 其他好文 > 详细

Stream 流

时间:2019-11-02 11:33:46      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:ret   sys   detail   code   col   简写   迭代器   from   arrays   

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 流

标签:ret   sys   detail   code   col   简写   迭代器   from   arrays   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!