0

I have a record for Employees:

public record Employee(
String name, 
String id, 
string imm_supervisor, 
){}

I have a stream of Employee objects, and I want to extract a hashmap that gives me a mapping between each imm_supervisor and the amount of employees that the supervisor directly supervises.

I'm frankly confused by documentation, and I've been getting errors not knowing how stream this properly. This is as close as I got:

 Map<String, Integer> mp = streamWithEmployees.map(x->supervisorofEmployee(x)).collect(groupingBy(/*String*/, counting()));

supervisorofEmployee(employee) returns a string, imm_supervisor. I'm not sure how to grab the returned strings from the map and put them into the map.

Hope this makes sense.

  • Use the answer on the first linked question if you want to keep `.map(x->supervisorofEmployee(x))`. Otherwise, use the answer on the second linked question. The immediate replacement for `/*String*/` is `Function.identity()`, but you can get the count with this stream without using `.map()`. – ernest_k Nov 13 '21 at 18:50
  • If you're using `record` it's definitely beyond Java 8. Use `MapstreamWithEmployees.collect(Collectors.groupingBy(Employee::imm_supervisor, counting()));` If `Integer` is _needed_, `Collectors.summingInt` can be used: `Collectors.groupingBy(Employee::imm_supervisor, Collectors.summingInt(x -> 1));` – Nowhere Man Nov 13 '21 at 19:00

0 Answers0