2
IntStream is = IntStream.of(1,2,3);

IntUnaryOperator un = IntUnaryOperator.identity();

is.forEach(s -> un.applyAsInt(s));

forEach method can only take consumer as the argument then how does it compile successfully with applyAsInt man method which returns int?

Can anyone please explain the reason behind this?

Naman
  • 27,789
  • 26
  • 218
  • 353
vidhi shah
  • 31
  • 5

2 Answers2

3

The code in question

is.forEach(s -> un.applyAsInt(s));

can also be represented as :

is.forEach(new IntConsumer() {
    @Override
    public void accept(int s) {
        un.applyAsInt(s);  // return type ignored
    }
});

which can help you understand that despite applyAsInt returning int, the returned value is ignored within forEach.

Naman
  • 27,789
  • 26
  • 218
  • 353
1

Because "s -> un.applyAsInt(s)" is a Consumer

Twister
  • 161
  • 4
  • can you please elaborate why it is consumer? because my understanding is applyAsInt is function which takes argument and returns the same argument. the return type is not void – vidhi shah Feb 20 '19 at 11:17
  • why do you concern accept here? Function applyAsInt receive a int then return a int. So we have a IntConsumer: s -> un.applyAsInt(s). Your code can be also rewriten: is.forEach(un::applyAsInt) – Twister Feb 20 '19 at 11:20
  • ok, it is somewhat confusing because I think I have habit of seeing System.out.print in consumer. – vidhi shah Feb 20 '19 at 11:24
  • Got your confusing. Consumer use method "accept", it receive value then return nothing. Supplier use method "get", it receive nothing then return object – Twister Feb 20 '19 at 11:35
  • thank you for the explanation – vidhi shah Feb 20 '19 at 11:42
  • 1
    @Twister Just to note that `IntConsumer` doesn't really extend a `Consumer`, its a specialization of the same though and the `IntStream.forEach` accepts a `IntConsumer` rather than a `Consumer`. – Naman Feb 20 '19 at 11:59