I am not quite able to understand why the line1
and line2
in the following code compiles just fine? Can forEach
method in Java Stream
take a Function
functional interface as argument?
On line 1
, shouldn't the IntConsumer
functional interface that forEach
takes have a void
return whereas the value1.incrementAndGet()
does return a long
?
Similarly, wouldn't ++value2[0]
return a long
and make the code not compile?
public class ShouldItCompile {
public static void main(String[] args) {
AtomicLong value1 = new AtomicLong(0);
final long[] value2 = {0};
IntStream.iterate(1, i -> 1).limit(100).parallel().forEach(i -> value1.incrementAndGet());//line1
IntStream.iterate(1, i -> 1).limit(100).parallel().forEach(i -> ++value2[0]);//line2
System.out.println(value1+" "+value2[0]);
}
}