Reputation: 2795
when I was coding, one question occurred to me, which is if the value part(Integer) in the HashMap is able to auto-increment in the following scenario?
Map<String, Integer> dictionary = new HashMap<String, Integer>();
dictionary.put("a",1);
dictionary.put("b",1);
Upvotes: 0
Views: 13160
Reputation: 19347
Consider using an AtomicInteger
:
Map<Key, AtomicInteger> dictionary =
new HashMap<String, AtomicInteger>();
dictionary.get(key).incrementAndGet();
Also consider using a for
loop to simplify the code.
Upvotes: 3
Reputation: 770
You can create a support class:
public class HashMapInteger<K> extends HashMap<K,Integer> {
public void increment(K key) {
if(super.containsKey(key))
super.put(key,super.get(key)+1);
else
super.put(key,new Integer(1));
}
public void increment(K key, int val) {
if(super.containsKey(key))
super.put(key,super.get(key)+val);
else
super.put(key,new Integer(val));
}
}
To use it:
HashMapInteger<String> map = new HashMapInteger<String>();
map.increment("abc");
map.increment("abc");
System.out.println(map.get("abc"));//Output is 2
Upvotes: 0
Reputation: 533780
The simplest and fastest solution is to use TObjectIntHashMap
TObjectIntHashMap<String> map = new TObjectIntHashMap<String>();
public void add(String str){
map.adjustOrPutValue(str, 1, 1);
}
Trove support primitives in collections making them more efficient, and in this case has a method which does what you need.
Upvotes: 1
Reputation: 268
You can use a Multiset from the Guava framework which is open sourced by Google.
Using Multiset can greatly simplify your life.
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();
}
Compare to the traditional way that uses ordinary HashMaps:
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);
}
}
Even if you use mutable counters as the value of the HashMap, the code is still very cumbersome.
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();
}
Upvotes: 4
Reputation: 882
You can write a custom class AutoIncrementHashMap
which internally uses a HashMap
, have an auto incrementing variable count
and a put(String)
method which adds a String
member and increments the counter
every time.
Upvotes: 2