1

I have been reviewing Oracle Java tutorial for Stream.collect reduction found here: https://docs.oracle.com/javase/tutorial/collections/streams/reduction.html

Looking at the sample code, the tutorial creates a new Averager class implementing IntConsumer, that is implementing accept which just take a single argument making it a 'single' Consumer.

class Averager implements IntConsumer
{
  private int total = 0;
  private int count = 0;

  public double average() {
    return count > 0 ? ((double) total)/count : 0;
  }

  public void accept(int i) { total += i; count++; }

  public void combine(Averager other) {
    total += other.total;
    count += other.count;
  }
}

It is used later by this code:

Averager averageCollect = roster.stream()
  .filter(p -> p.getGender() == Person.Sex.MALE)
  .map(Person::getAge)
  .collect(Averager::new, Averager::accept, Averager::combine);

My question is: the collect method takes a Supplier and two BiConsumers, but it appears Averager::accept and Averager::combiner are just Consumer methods as they take only one argument.

The code works, so I'm just missing something. Any help appreciated.

Nazkter
  • 1,040
  • 1
  • 11
  • 31
djtek
  • 11
  • 1
  • 1
    *it appears Averager::accept and Averager::combiner are just Consumer methods as they take only one argument.* No, the first argument is the `Averager` object itself. Read up on [method references](https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html). – shmosel Aug 22 '17 at 01:29

0 Answers0