Ritu Raj Shrivastava :
I want to print department names and number of employees working in each department!
Why forEach of stream is not Working?
ArrayList<Employee> list = EmployeeRepository.myList;
public Double getTotalSalary(){
return list.stream().map(e -> e.getSalary()).reduce(0.0,(s1,s2) -> s1+s2);
}
public void departmentNamesAndEmployeeCount(){
list.stream().collect(Collectors.groupingBy(Employee::getDepartment,Collectors.counting())).forEach(hm -> system.out::println); /// Compilation Error on this Line.
}
YCF_L :
groupingBy
return a Map<key, value>
, to print a Map with forEach:
- forEach in your case of Map, took
BiConsumer
two params key and values: - You can't use method reference
::
as you do, you have to use a simpleprintln
Your code should be:
.forEach((k, v) -> System.out.println(k + " " + v));
In the first method getTotalSalary
, You simply do:
return list.stream()
.mapToDouble(Employee::getSalary)
.sum();