Reputation: 1
I'd like to have a vector which contains some (possibly many) Hashmaps of which have a string as the key and an integer as the value. How could I check whether my vector of Hashmaps already contains a certain key, and if so, increment the corresponding key's value by 1?
What I am trying to accomplish is to count the number of times a word occurs in a document. My thinking was that I could use a HashMap to store the number of times a word occurs. But I want to check if my vector already contains a map with a given word before adding a new map to my vector. If my vector DOES contain a map with the given word, increment the value field (in this case numOfTimesOccurredSoFar).
Is this possible?
Upvotes: 0
Views: 3317
Reputation: 10003
import java.util.Map;
import java.util.TreeMap;
public class So13315440 {
void add(String word) {
if(map.containsKey(word))
map.put(word,map.get(word)+1);
else map.put(word,1);
}
void run() {
add("foo");
add("foo");
add("bar");
System.out.println(map);
}
public static void main(String[] args) {
new So13315440().run();
}
Map<String,Integer> map=new TreeMap<String,Integer>();
}
Upvotes: 0
Reputation: 21
Unless I misunderstand what you want to do, I see no reason to store maps in a vector when you can use a single map to map words to word count. For each word, check if the map has that word as a key, and if it does, add 1 to the value mapped to the word. If the word isn't in the map yet, add a new key-value pair.
Upvotes: 2