This post will discuss how to transform HashMap key-value pairs from one type into another type in Java.

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}

 
This is equivalent to:

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}

 
Similarly, 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.

That’s all about transforming HashMap in Java.