分类 标签 存档 订阅 搜索

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

212 浏览0 评论

本文由黑壳博客转发  

  

本文来源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

黑壳博客 blog.bhusk.com

E-mail:[email protected]

本文由 黑壳博客的壳叔 创作或转载,采用 知识共享署名 3.0 中国大陆许可协议 进行许可。

可自由转载、引用,但需署名作者且注明文章

评论  
留下你的脚步
推荐阅读