Java 8 Streams API – Convert a List to Map


In this post I will show how to convert a given List to a Map. If you are preparing for an interview and have mentioned Java 8 in your resume, you are very likely to face this or a similar question. So, it might help to spend a couple of minutes on this.


We are given a list of some user defined objects, say, User.

We need to use Java 8’s Stream API to convert this list into a Map where
key = id field of the User object &
value = User object itself.





The complete code would look like:


This solution would work fine as long a the keys we specify are unique. If there are duplicate keys, this method will throw an exception. To illustrate, let’s add a duplicate in your input list, something like:

While the duplicate key “Three” is encountered an exception will be thrown as shown below:


This situation is easy to fix using another API method as shown below.

Handling Duplicate Keys


(oldVal, newVal) -> oldVal is the Binary merge function using which you specify which value you prefer to keep once a duplicate is encountered.
In this example old value is being kept and newer duplicate is being ignored.


You should read more about these methods in the official documentation.