[Java基礎]讓Map value自增

來源:互聯網
上載者:User

標籤:...   contains   ast   tin   nal   lse   ash   util   java   

需求:我要在map中判斷是否存在key,存在則讓key對應的value = value+1,否則設定<key,value=1>

代碼實現方式如下:

ContainsKey
import java.util.HashMap;import java.util.Map;...Map<String, Integer> freq = new HashMap<String, Integer>();...int count = freq.containsKey(word) ? freq.get(word) : 0;freq.put(word, count + 1);
TestForNull
import java.util.HashMap;import java.util.Map;...Map<String, Integer> freq = new HashMap<String, Integer>();...Integer count = freq.get(word);if (count == null) {    freq.put(word, 1);}else {    freq.put(word, count + 1);}
AtomicLong
import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ConcurrentMap;import java.util.concurrent.atomic.AtomicLong;...final ConcurrentMap<String, AtomicLong> map =     new ConcurrentHashMap<String, AtomicLong>();...map.putIfAbsent(word, new AtomicLong(0));map.get(word).incrementAndGet();
Trove
import gnu.trove.TObjectIntHashMap;...TObjectIntHashMap<String> freq = new TObjectIntHashMap<String>();...freq.adjustOrPutValue(word, 1, 1);
MutableInt
import java.util.HashMap;import java.util.Map;...class MutableInt {  int value = 1; // note that we start at 1 since we‘re counting  public void increment () { ++value;      }  public int  get ()       { return value; }}...Map<String, MutableInt> freq = new HashMap<String, MutableInt>();...MutableInt count = freq.get(word);if (count == null) {    freq.put(word, new MutableInt());}else {    count.increment();}

還有Java8的方法:  

Map.merge(key, 1, Integer::sum) //如果key存在,就調用sum 1 到map的value,如果key不存在,put(key,1)

時間方面,執行1000次數,如下所示
                 time, mskolobokeCompile  18.8koloboke         19.8trove            20.8fastutil         22.7mutableInt       24.3atomicInteger    25.3eclipse          26.9hashMap          28.0hppc             33.6hppcRt           36.5

 



[Java基礎]讓Map value自增

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.