Java中Map的merge、compute、computeIfAbsent、computeIfPresent的用法以及使用场景(二)

本文由黑壳博客转发

本文来源Java中Map的merge、compute、computeIfAbsent、computeIfPresent的用法以及使用场景(二)

一篇一笑

margin-right:-5px

正文

Java中Map的merge、compute、computeIfAbsent、computeIfPresent的用法以及使用场景(二)
compute,computeIfPresent使用场景
computeIfPresent的用法
compute:V compute(K key,
BiFunction < ? super K, ? super V, ? extends V> remappingFunction)

compute的方法,指定的key在map中的值进行操作 不管存不存在。

现在我们要做一个操作,统计字符串中每一个的 单词出现的次数。

具体实现

      public static void main(String[] args) {  
  
        Map<String, Integer> wordCounts = new ConcurrentHashMap<>(10);  
        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);  
        for (String t : s.split(" ")) {  
            wordCounts.compute(t, (k, v) ->{  
                    if(null == v) v = 0;  
                    v= v + 1;  
                    return v;  
            });  
        }  
        System.out.println(wordCounts);  
    }  

结果:
{=1, consetetur=1, eirmod=1, tempor=1, sadipscing=1, labore=1, magna=1, aliquyam=1, erat=2, et=1, elitr,=1, dolor=2, nonumy=2, dolore=1, sed=3, iam=1, Lorem=1, invidunt=1, amet=2, ipsum=1, diam=2, sit=2, ut=1}

computeIfPresent的用法
computeIfPresent:V computeIfPresent(K key,
BiFunction < ? super K, ? super V, ? extends V> remappingFunction)

computeIfPresent 的方法,对 指定的 在map中已经存在的key的value进行操作。只对已经存在key的进行操作

现在我们要做一个操作,统计字符串中指定的 单词出现的次数。

具体实现

  public static void main(String[] args) {  
  
        Map<String, Integer> wordCounts = new ConcurrentHashMap<>(10);  
        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);  
        for (String t : s.split(" ")) {  
            wordCounts.computeIfPresent(t, (k, v) -> v + 1);  
        }  
        System.out.println(wordCounts);  
    }  

结果:
{sed=3}

About

欢迎在评论写下你的程序员趣事~~

欢迎加入我们的小组织 ,大家都叫壳叔,期待你的到来。

欢迎关注公众号

微信公众号

这是我们的Group

黑壳家根据地 Q群:200408242

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值