The Stream.collect Method

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

//The following pipeline uses the Averager class and the collect method to 
//calculate the average age of all male members:

	
Averager averageCollect = roster.stream()
    .filter(p -> p.getGender() == Person.Sex.MALE)
    .map(Person::getAge)
    .collect(Averager::new, Averager::accept, Averager::combine);
                   
System.out.println("Average age of male members: " +
    averageCollect.average());

Unlike the reduce method, which always creates a new value when it processes an element, the collect method modifies, or mutates, an existing value.

The collect operation may take three arguments: supplier, accumulator and combiner.

Related concepts

The Stream.collect Method

The Stream.collect Method — Structure map

Clickable & Draggable!

The Stream.collect Method — Related pages: