Print Map using forEach of Stream API

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:

  1. forEach in your case of Map, took BiConsumer two params key and values:
  2. You can't use method reference :: as you do, you have to use a simple println

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();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31403&siteId=1