forEach method is accepting a lambda expression which returns a value. Why I am not getting compilation issue for the below code?

问题: AtomicInteger value1 = new AtomicInteger(0); IntStream.iterate(1, x -> 1).limit(100).parallel().forEach(y -> value1.incrementAndGet()); In the above code, forEach...

问题:

AtomicInteger value1 = new AtomicInteger(0);
IntStream.iterate(1, x -> 1).limit(100).parallel().forEach(y -> value1.incrementAndGet());

In the above code, forEach is accepting a lambda expression which is returning a value. But forEach on stream accepts only Consumer which can't return any value from its accept method. Why I am not getting compilation error for this ?


回答1:

Why I am not getting compilation error for this ?

Because the value returned by the method is ignored while it is consumed.

You can also look at it like the accept method of IntConsumer would now look like :

new IntConsumer() {
    @Override
    public void accept(int y) {
        value1.incrementAndGet();
    }
});
  • 发表于 2019-03-10 15:56
  • 阅读 ( 172 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除