I have the following code to count the instances of different strings in an array;
String words[] = {"the","cat","in","the","hat"};
HashMap<String,Integer> wordCounts = new HashMap<String,Integer>(50,10);
for(String w : words) {
Integer i = wordCounts.get(w);
if(i == null) wordCounts.put(w, 1);
else wordCounts.put(w, i + 1);
}
Is this a correct way of doing it? It seems a bit long-winded for a simple task. The HashMap
result is useful to me because I will be indexing it by the string.
I am worried that the line
else wordCounts.put(w, i + 1);
could be inserting a second key-value
pair due to the fact that
new Integer(i).equals(new Integer(i + 1));
would be false, so two Integers
would end up under the same String
key bucket, right? Or have I just over-thought myself into a corner?
HashMap don't allow duplicate keys, so there is no way to have more than one SAME key-value pairs in your map.
Yes you are doing it correct way. HashMap replaces values if same key is provided.
From Java doc of
HashMap#put
Your code looks fine to me and there is no issue with it. Thanks to Java 8 features it can be simplified to:
the follwowing code
would print out.
Here is a String-specific counter that should be genericized and have a sort by value option for toString(), but is an object-oriented wrapper to the problem, since I can't find anything similar:
Your code is perfectly fine. You map strings to integers. Nothing is duplicated.
Your code will work - but it would be simpler to use
HashMultiset
from Guava.