Stream 流

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


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

猜你喜欢

转载自www.cnblogs.com/wanghuanyeah/p/11780988.html