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.

Download  Run Code

Output:

{1=ONE, 2=TWO}

 
Note that an exception will be thrown for a null input. This can be handled as follows:

Download  Run Code

Output:

{1=ONE, 2=TWO, 3=null}

2. Using for loop

Here’s a version without streams, using a for loop:

Download  Run Code

Output:

{1=ONE, 2=TWO}

That’s all about applying a function to each entry of a Map in Java.