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

Consider the following Color class, which contains two private fields – colorName and colorCode. They represent the 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 Stream

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 on the map, we can provide a merge method 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 the toMap() method, as shown below:

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

Download  Run Code

Output:

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

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