Transform HashMap in Java 8

In this post, we will see how to transform HashMap key-value pairs from one Type to another Type in Java 8.


 

1. Transforming HashMap<K1, V> to HashMap<K2, V>

 

Download   Run Code

Output:

{1=One, 2=Two, 3=Three}

 

2. Transforming HashMap<K, V1> to HashMap<K, V2>

 

Download   Run Code

Output:

{One=1, Two=2, Three=3}

 

3. Transforming HashMap<K1, V1> to HashMap<K2, V2>

 

Download   Run Code

Output:

{1=1, 2=4, 3=9}

 
In similar way, we can convert HashMap of other types. For instance, we can use String.valueOf() method in place of Integer.parseInt() to convert an Integer key/value to a String.

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of