1

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.

0

1 Answer 1

6

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)
Sign up to request clarification or add additional context in comments.

2 Comments

To be on the safe side, make sure that the list does not contain duplicate ids by using distinct() or by providing a merging function when collecting to map.
Manish, as @Eritrean pointed out, take care of the possibility of receiving a non-unique id list. I have updated the answer with the relevant info.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.