ConcurrentHashMap JDK 8何时使用computeIfPresent [英] ConcurrentHashMap JDK 8 when to use computeIfPresent

查看:300
本文介绍了ConcurrentHashMap JDK 8何时使用computeIfPresent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jdk 8的新版Concurrent Hash Map有两个新方法。

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

computeIfAbsent

computeIfPresent

putIfAbsent - 旧方法

我理解 putIfAbsent computeIfAbsent 的用例。
但是当我使用 computeIfPresent 时,我不确定这些情况。
如果我现在有computeIfPresent,为什么我还需要putIfAbsent。
putIfAbsent会创建至少一个额外的值实例。

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?

推荐答案

正如其他答案中所提到的:即使有新的,更强大的方法引入,也始终保留方法以实现向后兼容。

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

关于 computeIfPresent的用例:可能很难找到一个足够小的例子看起来做作,仍然令人信服。通常,此方法的目的是以任何形式更新现有值。

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.

一个例子可能是(约束)字数:对于给定的一组字,一个存储初始计数 0 在地图中。然后,处理一系列单词:每当从初始集中找到单词时,其计数增加1:

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);
        }
        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)

这篇关于ConcurrentHashMap JDK 8何时使用computeIfPresent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆