This post will discuss how to convert a list to a map in Java.

Consider the following Color class, which contains two private fields – name and code. They represent the color name and its corresponding HTML color code, respectively.

 
In the following example, we’ll see how we can construct a map from a list of Color objects.

Download  Run Code

Output:

List : [RED=#FF0000, BLUE=#0000FF, GREEN=#008000]
Map : {RED=#FF0000, BLUE=#0000FF, GREEN=#008000}

 
This can be easily done using Java 8 Stream:

Download  Run Code

Output:

List : [RED=#FF0000, BLUE=#0000FF, GREEN=#008000]
Map : {RED=#FF0000, BLUE=#0000FF, GREEN=#008000}

 
We can also use lambda expressions instead of method references.

 
Collectors class provides several overloaded versions of the toMap() method:

1. If duplicate keys are present on the map, an IllegalStateException is thrown when the collection operation is performed.

We can provide a merge method used to resolve collisions between values associated with the same key (normally, either the old value or new value in the stream takes precedence).

 
2. The default implementation of toMap() doesn’t specify the Type of the map object returned. We can supply the Type of map in another overloaded version of the toMap() method, as shown below:

 
Here’s is one more example where we have a list of specific ASCII characters, and we’ll construct a map out of it that represents the ASCII character table.

Download  Run Code

Output:

{A=65, B=66, C=67, D=68}

 
This is equivalent to:

Download  Run Code

Output:

{A=65, B=66, C=67, D=68}

Creating MultiMap

We can use Collectors.groupingBy() to perform the equivalent of a database cascaded “group by” operation on input elements, as shown below:

Download  Run Code

Output:

{Car=[Mercedes, Audi, BMW], Bike=[Harley Davidson, Triumph]}

 
Here’s an equivalent version without using the Stream API.

Download  Run Code

Output:

{Car=[Mercedes, Audi, BMW], Bike=[Harley Davidson, Triumph]}

That’s all about converting List to Map in Java.