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

image

一篇一笑

<b>margin-right:-5px</b>

image

正文

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中的值進(jìn)行操作 不管存不存在。

現(xiàn)在我們要做一個操作,統(tǒng)計字符串中每一個的 單詞出現(xiàn)的次數(shù)。

具體實現(xiàn)

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

結(jié)果:
{=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中已經(jīng)存在的key的value進(jìn)行操作。只對已經(jīng)存在key的進(jìn)行操作

現(xiàn)在我們要做一個操作,統(tǒng)計字符串中指定的 單詞出現(xiàn)的次數(shù)。

具體實現(xiàn)

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

結(jié)果:
{sed=3}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容