Convert List to Map in Java

In this post, we will discuss how to convert List to Map in Java.


 

Consider below Color class which contains two private fields – name and code. They represents color name and its corresponding HTML color code respectively.

 

 
In below example, we will see how we can construct a Map from List of Color objects.

 

Download   Run Code

Output:

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

 

Using Java 8 streams –

 

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 toMap() method –

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

We can provide a merge function which is 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 toMap() method as shown below:

 


 

Here’s is one more example where we have a list of specific ASCII characters and we will construct a Map out of it that represent ASCII character table.

 

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]}

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz