• [Java基础]让Map value自增


    需求:我要在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, ms
    kolobokeCompile  18.8
    koloboke         19.8
    trove            20.8
    fastutil         22.7
    mutableInt       24.3
    atomicInteger    25.3
    eclipse          26.9
    hashMap          28.0
    hppc             33.6
    hppcRt           36.5


    欢迎关注Java流水账公众号
  • 相关阅读:
    Pycharm 创建py文件自动添加文件头注释
    Python 面向对象编程
    selenium webdriver入门
    测试工程师进阶必读书目
    Python好酷|抓包神器 mitmproxy
    TKinter图形化编程库
    Web UI自动化框架大比拼
    DTSE Tech Talk | 第10期:云会议带你入门音视频世界
    密码学系列之:使用openssl检测网站是否支持ocsp
    密码学系列之:在线证书状态协议OCSP详解
  • 原文地址:https://www.cnblogs.com/guofu-angela/p/9432668.html
Copyright © 2020-2023  润新知