gpt4 book ai didi

java - HashMap值自增

转载 作者:行者123 更新时间:2023-12-01 06:45:32 24 4
gpt4 key购买 nike

在写代码的时候,我想到了一个问题,HashMap中的值部分(Integer)在下面的场景中是否能够自增?

Map<String, Integer> dictionary = new HashMap<String, Integer>();    
dictionary.put("a",1);
dictionary.put("b",1);

最佳答案

您可以使用 Multiset来自Guava由 Google 开源的框架。

使用 Multiset 可以极大地简化您的生活。

    Multiset<String> set = HashMultiset.create();
set.add("abc"):
set.add("acd");
set.add("abc");

// use set.count(Object) to get the counter of the object
int c = set.count("abc");

// or iterate through the set to get each object and its count
for (Multiset.Entry<String> entry : set.entrySet()){
String str = entry.getElement();
int count = entry.getCount();
}

与使用普通HashMap的传统方式相比:

    Map<String, Integer> map = new HashMap<String, Integer>();

public void add(String str){
Integer oldValue = map.get(str);
if (oldValue == null){
map.put(str, 1);
} else{
map.put(str, oldValue + 1);
}
}

即使使用可变计数器作为HashMap的值,代码仍然很繁琐。

    Map<String, AtomicInteger> map = new HashMap<String, AtomicInteger>();

public void add(String str){
AtomicInteger counter = map.get(str);
if (counter == null){
counter = new AtomicInteger();
map.put(str, counter);
}
counter.incrementAndGet();
}

关于java - HashMap值自增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15996164/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com