Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

Like 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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
21:3,
25:2
}

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

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 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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading