Java stream api using reference of original object within chain

Viewed 87

I am trying to create a Map from a list, whereas value of Map would be a result of some transformation, this is how my code looks like.

empIdList.stream()
         .map(id-> getDepartment(id))
         .collect(Collectors.toMap(id, department:String -> department)

in this above example I am looking to use id as key and department as value. can you please help me achieving my expected results.

1 Answers

You could avoid the map function and directly invoke collect

empIdList.stream()    
         .collect(Collectors.toMap(Function.identity(), this::getDepartment);

If the list does not have unique ids, then it would result in an IllegalStateException so:

  1. Either pass a Set of ids instead of a List if possible.
  2. OR use distinct() in between stream() and collect().
  3. OR provide a dummy merging function as the third argument to toMap: Collectors.toMap(Function.identity(), this::getDepartment, (a,b) -> a)
Related