Transform HashMap in Java 8 and above
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>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; class Main { public static void main(String[] args) { Map<String, String> map = new HashMap<>(); map.put("1", "One"); map.put("2", "Two"); map.put("3", "Three"); Map<Integer, String> hashMap = map.entrySet().stream().collect(Collectors.toMap( entry -> Integer.parseInt(entry.getKey()), entry -> entry.getValue())); System.out.println(hashMap); } } |
Output:
{1=One, 2=Two, 3=Three}
2. Transforming HashMap<K,V1> to HashMap<K,V2>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; class Main { public static void main(String[] args) { Map<String, String> map = new HashMap<>(); map.put("One", "1"); map.put("Two", "2"); map.put("Three", "3"); Map<String, Integer> hashMap = map.entrySet().stream().collect(Collectors.toMap( entry -> entry.getKey(), entry -> Integer.parseInt(entry.getValue())) ); System.out.println(hashMap); } } |
Output:
{One=1, Two=2, Three=3}
This is equivalent to:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.HashMap; import java.util.Map; class Main { public static void main(String[] args) { Map<String, String> map = new HashMap<>(); map.put("One", "1"); map.put("Two", "2"); map.put("Three", "3"); Map<String, Integer> hashMap = new HashMap<>(); for (Map.Entry<String, String> entry : map.entrySet()) { if (hashMap.put(entry.getKey(), Integer.parseInt(entry.getValue())) != null) { throw new IllegalStateException("Duplicate key"); } } System.out.println(hashMap); } } |
Output:
{One=1, Two=2, Three=3}
3. Transforming HashMap<K1,V1> to HashMap<K2,V2>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; class Main { public static void main(String[] args) { Map<String, String> powerMap = new HashMap<>(); powerMap.put("1", "1"); powerMap.put("2", "4"); powerMap.put("3", "9"); Map<Integer, Integer> hashMap = powerMap.entrySet().stream().collect(Collectors.toMap( entry -> Integer.parseInt(entry.getKey()), entry -> Integer.parseInt(entry.getValue()))); System.out.println(hashMap); } } |
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.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)