The Oracle trails on reduction with streams gives an example of how to convert a collection of people into a map containing the average age based on gender. It uses the following Person
class and code:
public class Person {
private int age;
public enum Sex {
MALE,
FEMALE
}
private Sex sex;
public Person (int age, Sex sex) {
this.age = age;
this.sex = sex;
}
public int getAge() { return this.age; }
public Sex getSex() { return this.sex; }
}
Map<Person.Sex, Double> averageAgeByGender = roster
.stream()
.collect(
Collectors.groupingBy(
Person::getSex,
Collectors.averagingInt(Person::getAge)));
The above stream code works great, but I wanted to see how to do the same operation while using a custom implementation of a collector. I could find no complete example of how to do this either on Stack Overflow or the net. As to why we might want to do this, as an example, perhaps we would want to compute some kind of weighted average involving the age. In this case, the default behavior of Collectors.averagingInt
would not suffice.
Collectors.summarizingInt
, which returns an IntSummaryStatistics and is quite helpful whenCollectors.averagingInt
does not suffice.