Apply a function to each entry of a Map in Java
This post will discuss how to apply a function to each entry of a Map in Java.
1. Using Java 8
Since Java 8, you can use the replaceAll() method, which replaces each entry’s value with the result of invoking the given function on it. The following solution demonstrates its usage by applying the toUpperCase() function to each value in the map.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { Map<Integer, String> map = new HashMap<>(); map.put(1, "one"); map.put(2, "two"); map.replaceAll((key, value) -> value.toUpperCase()); System.out.println(map); } } |
Output:
{1=ONE, 2=TWO}
Note that an exception will be thrown for a null input. This can be handled as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { Map<Integer, String> map = new HashMap<>(); map.put(1, "one"); map.put(2, "two"); map.put(3, null); map.replaceAll((key, value) -> value != null ? value.toUpperCase(): null); System.out.println(map); } } |
Output:
{1=ONE, 2=TWO, 3=null}
2. Using for loop
Here’s a version without streams, using a for loop:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.*; public class Main { public static void main(String[] args) { Map<Integer, String> map = new HashMap<>(); map.put(1, "one"); map.put(2, "two"); for (Map.Entry<Integer, String> entry : map.entrySet()) { String value = entry.getValue(); if (value != null) { entry.setValue(value.toUpperCase()); } } System.out.println(map); } } |
Output:
{1=ONE, 2=TWO}
That’s all about applying a function to each entry of a Map 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 :)