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.

2
  • 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(). Commented Nov 13, 2021 at 18:50
  • If you're using record it's definitely beyond Java 8. Use Map<String, Long>streamWithEmployees.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)); Commented Nov 13, 2021 at 19:00

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.