Search code examples
javalambdajava-8functional-interface

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 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 ?


Solution

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