The new version of Concurrent Hash Map of jdk 8 has two new Methods.
computeIfAbsent
computeIfPresent
putIfAbs
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 wordCounts = new LinkedHashMap();
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);
}
System.out.println(wordCounts);
}
}
(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)