Java流,带和不带forEach之间的区别 [英] Java stream, difference between with and without forEach

查看:81
本文介绍了Java流,带和不带forEach之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用(*) forEach 和不使用有什么区别?输出是什么,为什么?我知道没有 forEach 不会打印任何内容...但是为什么需要查看?

What is the difference between with (*) forEach and without? What is the output and why? I know without forEach nothing will be printed...but why peek is needed?

正如我对 peek 所知道的,您必须对 System.out.println 的结果流进行某些操作……但是,似乎没有在这里完成,它仍然可以运行....

As I know for peek you have to do something with the resulting stream for System.out.println to do anything... however it doesn't seems to be done here, and it still runs....

public class NaturalNumbers
       implements Supplier<Integer> {
 private int i = 0;
 public Integer get() { return ++i; }
}

public static void main(String[] args) {
 Stream<Integer> s =
                Stream.generate(new NaturalNumbers());

 s.limit(5)
  .peek( System.out::println )
  .forEach( System.out::println );/// ׂ (*)
{

推荐答案

peek 只是在流中进行 peek 的一种方法,它不会改变它,但是peek函数将接收流中的所有元素.

peek is just a way to peek inside the stream, it doesn't change it but the function in peek will receive all the elements that are in the stream.

forEach 是一个终端操作,它将消耗流中的所有数据并返回 void .

forEach is an terminal operation that will consume all the data in the stream and return void.

以上代码的结果将每个数字打印两次,当您删除 peek 时,您将只能打印一次数字.

The result of the above code will be each number printed twice, when you remove peek you will get the numbers printed only once.

如果删除 forEach ,您将不会获得任何输出,因为流将在终端操作之前不会执行操作(例如 forEach count ).

If you remove forEach you wont' get any output because stream won't execute the actions until the terminal operation (like e.g. forEach, count) is encountered.

这篇关于Java流,带和不带forEach之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆