Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

Map is a commonly used data structure that contains key-value associations. Java offers a variety of methods for manipulating map entries. Since Java 8, some new members have joined the Map family.

putIfAbsent() and computeIfAbsent() are two of them. We frequently used these two methods for adding entries. While they might seem similar at first glance, they have distinct behaviors and use cases.

In this tutorial, we’ll discuss the difference between these two methods.

2. Introduction

Before diving into the discussion of the difference, let’s establish some common ground.

Both putIfAbsent() and computeIfAbsent() are methods provided by the Map interface in Java, and they share a common goal: adding a key-value pair to a map if the key is absent. This behavior is particularly useful when we want to prevent overwriting existing entries.

It’s worth noting that the “absent” covers two cases:

  • The key doesn’t exist in the map
  • The key exists, but the associated value is null

However, the two methods’ behaviors aren’t the same.

In this tutorial, we won’t discuss how to use these two methods in general. Instead, we’ll only focus on their differences, and we’ll look at their differences from three perspectives.

Also, we’ll use unit test assertions to demonstrate the differences. So next, let’s quickly set up our test examples.

3. Preparation

Since we’ll call putIfAbsent() and computeIfAbsent() to insert entries to a map, let’s first create a HashMap instance for all the tests:

private static final Map<String, String> MY_MAP = new HashMap<>();

@BeforeEach
void resetTheMap() {
    MY_MAP.clear();
    MY_MAP.put("Key A", "value A");
    MY_MAP.put("Key B", "value B");
    MY_MAP.put("Key C", "value C");
    MY_MAP.put("Key Null", null);
}

As we can see, we also created the resetTheMap() method with the @BeforeEach annotation. This method ensures MY_MAP contains the same key-value pairs for each test.

If we look at computeIfAbsent()’s signature, we see the method accepts the mappingFunction function to compute the new value:

default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) { ... }

Therefore, let’s create the Magic class to provide some functions:

private Magic magic = new Magic();

The Magic class is pretty straightforward. It only offers two methods: nullFunc() always returns null, and strFunc() returns a not-null string.

class Magic {
    public String nullFunc() {
        return null;
    }
 
    public String strFunc(String input) {
        return input + ": A nice string";
    }
}

To be fair, in our tests, all new map values used in both putIfAbsent() and computeIfAbsent() come from magic‘s methods.

4. The Return Value When the Key Is Absent

The common part of the two methods is “IfAbsent”. We’ve talked about the definition of “absent”. The first difference is the return values of the two methods in the “absent” case.

Let’s first look at the putIfAbsent() method:

// absent: putting new key -> null
String putResult = MY_MAP.putIfAbsent("new key1", magic.nullFunc());
assertNull(putResult);

// absent: putting new key -> not-null
putResult = MY_MAP.putIfAbsent("new key2", magic.strFunc("new key2"));
assertNull(putResult);

// absent: existing key -> null (original)
putResult = MY_MAP.putIfAbsent("Key Null", magic.strFunc("Key Null"));
assertNull(putResult);

As we can see from the above test, when absent, the putIfAbsent() method always returns null, no matter whether the new value is null or not.

Next, let’s execute the same test with computeIfAbsent() and see what it returns:

// absent: computing new key -> null
String computeResult = MY_MAP.computeIfAbsent("new key1", k -> magic.nullFunc());
assertNull(computeResult);

// absent: computing new key -> not-null
computeResult = MY_MAP.computeIfAbsent("new key2", k -> magic.strFunc(k));
assertEquals("new key2: A nice string", computeResult);

// absent: existing key -> null (original)
computeResult = MY_MAP.computeIfAbsent("Key Null", k -> magic.strFunc(k));
assertEquals("Key Null: A nice string", computeResult);

As the test shows, when absent, the computeIfAbsent() method returns the mappingFunction‘s return value.

5. When the New Value Is null

We know HashMap allows null values. So next, let’s try to insert a null value to MY_MAP and see how the two methods behave.

First, let’s look at putIfAbsent():

assertEquals(4, MY_MAP.size()); // initial: 4 entries
MY_MAP.putIfAbsent("new key", magic.nullFunc());
assertEquals(5, MY_MAP.size());
assertTrue(MY_MAP.containsKey("new key")); // new entry has been added to the map
assertNull(MY_MAP.get("new key"));

So, when the key doesn’t exist in the target map, putIfAbsent() will always add a new key-value pair to the map, even if the new value is null.

Now, it’s computeIfAbsent()’s turn:

assertEquals(4, MY_MAP.size()); // initial: 4 entries
MY_MAP.computeIfAbsent("new key", k -> magic.nullFunc());

assertEquals(4, MY_MAP.size());
assertFalse(MY_MAP.containsKey("new key")); // <- no new entry added to the map

As we can see, if mappingFunction returns null, computeIfAbsent() refuses to add the key-value pair to the map.

6. “compute” Is Lazy, “put” Is Eager

We’ve talked about two differences between the two methods. Next, let’s have a look at when the “value” part is provided by a method or function whether the two methods behave in the same way.

As usual, let’s look at the putIfAbsent() method first:

Magic spyMagic = spy(magic);
// key existent
MY_MAP.putIfAbsent("Key A", spyMagic.strFunc("Key A"));
verify(spyMagic, times(1)).strFunc(anyString());

// key absent
MY_MAP.putIfAbsent("new key", spyMagic.strFunc("new key"));
verify(spyMagic, times(2)).strFunc(anyString());

As we can see in the test above, we used the Mockito spy on the magic object to verify whether the strFunc() method was invoked or not. The test turns out that no matter whether the key exists or not, the strFunc() method is always called.

Next, let’s see how the computeIfAbsent() method handles mappingFunction:

Magic spyMagic = spy(magic);
// key existent
MY_MAP.computeIfAbsent("Key A", k -> spyMagic.strFunc(k));
verify(spyMagic, never()).strFunc(anyString()); // the function wasn't called

// key absent
MY_MAP.computeIfAbsent("new key", k -> spyMagic.strFunc(k));
verify(spyMagic, times(1)).strFunc(anyString());

As the test shows, computeIfAbsent() does exactly as its name implies, computing mappingFunction only in the “absent” case.  

Another everyday use case is when we work with something like Map<String, List<String>>:

  •  putIfAbsent(aKey, new ArrayList()) – No matter whether “aKey” is absent, a new ArrayList object is created
  • computeIfAbsent(aKey, k -> new ArrayList()) – A new ArrayList instance is created only if “aKey” is absent

Therefore, we should use putIfAbsent() when adding a key-value pair directly without any computation if the key is absent. On the other hand, computeIfAbsent() can be used when we need to compute the value and add the key-value pair if the key is absent.

7. Conclusion

In this article, we’ve discussed the differences between putIfAbsent() and computeIfAbsent() through examples. Knowing this difference is crucial for making the right choice in our code.

As always, the complete source code for the examples is available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.