1.stream.forEach() 与 collection.forEach()
虽然都是迭代方法,但执行结果完全不同。
List 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. * * This method should be overridden when the {@link #spliterator()} * method cannot return a spliterator that is {@code IMMUTABLE}, * {@code CONCURRENT}, or late-binding. (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 */
故①与②内部迭代得到的结果不一样。
Original: https://www.cnblogs.com/wanghuanyeah/p/11780988.html
Author: wanghuanyeah
Title: Stream 流
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/586199/
转载文章受原作者版权保护。转载请注明原作者出处!