veritas veritas - 1 year ago 338
Java Question

ConcurrentHashMap JDK 8 when to use computeIfPresent

The new version of Concurrent Hash Map of jdk 8 has two new Methods.



putIfAbsent - Old method

I understand the use cases of putIfAbsent and computeIfAbsent.
But i am not sure of the scenarios when i will use computeIfPresent.
Also why do i need putIfAbsent if i have computeIfPresent now.
putIfAbsent do create atleast one extra instance of the value.

Is the reason is only to have backward compatability?

Answer Source

As mentioned in the other answer: Methods will always be kept for backward compatibility, even if there are new, more "powerful" methods introduced.

Concerning the use case for computeIfPresent: It may be hard to find an example that is small enough to not look contrived and still be convincing. In general, the intention of this method is to update an existing value in any form.

One example could be a (constrained) word count: For a given set of words, one stores an initial count of 0 in the map. Then, a sequence of words is processed: Whenever one finds a word from the initial set, its count is increased by 1:

import java.util.LinkedHashMap;
import java.util.Map;

public class ComputeIfPresentExample 
    public static void main(String[] args) 
        Map<String, Integer> wordCounts = new LinkedHashMap<String, Integer>();

        String s = 
            "Lorem ipsum dolor sit amet consetetur iam nonumy sadipscing " + 
            "elitr, sed diam nonumy eirmod tempor invidunt ut erat sed " + 
            "labore et dolore magna dolor sit amet aliquyam erat sed diam";

        wordCounts.put("sed", 0);
        wordCounts.put("erat", 0);

        for (String t : s.split(" "))
            wordCounts.computeIfPresent(t, (k,v) -> v+1);

(Of course, things like this could be solved differently, but this is a rather frequent task in one or the other form, and the new method allows a rather concise and elegant solution)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download