Convert Set to Map in Java

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


 

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

 

 
Let’s construct a Map from Set of Color objects using colorName as key and colorCode as value:

 

Download   Run Code

Output:

Set : [WHITE=#FFFFFF, GRAY=#808080, BLACK=#000000]
Map : {WHITE=#FFFFFF, GRAY=#808080, BLACK=#000000}

 

Using Java 8 streams –

 

Download   Run Code

Output:

Set : [WHITE=#FFFFFF, GRAY=#808080, BLACK=#000000]
Map : {WHITE=#FFFFFF, GRAY=#808080, BLACK=#000000}

 
We can also use method references instead of lambda expressions.

 
Collectors class provides several overloaded versions of toMap() method –

1. If there are duplicate keys present in the map, we can provide a merge function which is used to resolve collisions between values associated with the same key.

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

 
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