私がコーディングしていたとき、次のシナリオで HashMap の値部分 (Integer) が自動インクリメントできるかどうかという1 つの疑問が浮かびました。
Map<String, Integer> dictionary = new HashMap<String, Integer>();
dictionary.put("a",1);
dictionary.put("b",1);
Google がオープンソース化したGuavaフレームワークのMultisetを使用できます。
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();
}
の使用を検討してくださいAtomicInteger
:
Map<Key, AtomicInteger> dictionary =
new HashMap<String, AtomicInteger>();
dictionary.get(key).incrementAndGet();
また、for
ループを使用してコードを簡素化することも検討してください。
AutoIncrementHashMap
を内部的に使用するカスタム クラスを記述しHashMap
、自動インクリメント変数count
と、メンバーput(String)
を追加して毎回インクリメントするメソッドを使用できます。String
counter
最も簡単で最速のソリューションは、TObjectIntHashMapを使用することです
TObjectIntHashMap<String> map = new TObjectIntHashMap<String>();
public void add(String str){
map.adjustOrPutValue(str, 1, 1);
}
コレクション内のプリミティブをサポートして、それらをより効率的にします。この場合、必要なことを行うメソッドがあります。