Search code examples
javajava-8java-stream

How can I use toMap() method instead of groupingBy()


I have a List<Employee>. Now I want to summarize them as how many employees of each age group.

In that employee list, there are 3 employees of age 21. And there are 2 employees of age 25.

So I wanted to show them in Map<Integer,Long> like

{
21:3,
25:2
}

I know I can do that using Collectors.groupingBy(). But out of curiosity, I wanted to know how I can use the Collectors.toMap() method instead. I tried the code below.

Code

@GetMapping("api/test/groupingby/age")
    public Map<Integer,Long> testtest2(){
        Optional<List<Employee>> optEmployees = service.getAllEmployees();
        
        List<Employee> lsEmployees = optEmployees.map(ls->ls).orElseThrow();
        
        
        lsEmployees.stream().map(emp->emp.getAge()).
        collect(Collectors.
                toMap(age->age, Collectors.counting(),(e1,e2)->e1,LinkedHashMap::new));
        
        return null;
    }

It is giving me the below compile time error.

enter image description here


Solution

  • You can use the toMap variant that accepts a merge function:

    Map<Integer,Integer> ageCounts = 
        lsEmployees.stream()
                   .collect(Collectors.toMap(Employee::getAge, 
                                             emp -> 1,
                                             (v1,v2)->v1+v2));
    
    • The keyMapper returns the Employee's age.
    • The valueMapper returns 1, so that the first time a certain age key is encountered, it is given the value 1.
    • The mergeFunction handles the case of the same key appearing multiple times. In this case adding the values of the two identical keys ensures that the resulting map will map each age to the number of Employees with that age.