Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Streams - Collecting to a Map With GroupingBy and Counting, But Count 0 If A Specific Field Is Null [duplicate]

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

like image 951
Melih Avatar asked Jan 01 '23 14:01

Melih


1 Answers

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.

like image 152
Ravindra Ranwala Avatar answered Jan 03 '23 04:01

Ravindra Ranwala