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
{
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..
>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
keyMapperreturns theEmployee‘s age. - The
valueMapperreturns1, so that the first time a certain age key is encountered, it is given the value1. - The
mergeFunctionhandles 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 ofEmployees with that age.
