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

Bhawani shankar Panda :
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 ?

Naman :

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();
    }
});

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=151689&siteId=1