To protect the question from "duplicate hunters", I need to mention that I did not think that the solution I am looking for is filtering. I did my search, never encounter an answer mentioning filtering.
I have a list of objects with a class like that:
class Person {
String gender;
String income;
String petName;
}
I want to collect this List into a map, groupingBy gender, and counting the pets they have, and of course need to pass 0 if petName is null.
Map<String, Long> mapping = people
.stream()
.collect(Collectors.groupingBy(Person::gender, Collectors.counting());
Without implementing the Collector interface and it's 5 methods( Because I am already trying to get rid of another custom collector) How can I make this to not count the object if it's petName
field is null
.
I can benefit from Java-11
First, group all the people by their gender, and then use the filtering collector to filter out the people with null names. Finally, use the counting downstream collector to count the number of elements belong to each category. Here's how it looks.
Map<String, Long> peopleCntByGender = people.stream()
.collect(Collectors.groupingBy(Person::getGender,
Collectors.filtering(p -> p.getPetName() != null,
Collectors.counting())));
However, the filtering collector is only available in Java9, hence if you are using Java8 and can't migrate to Java9 that easily, consider writing your own custom filtering
collector and use it here. This answer or JDK 9 source code may help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With