Skip to content
Kango edited this page May 19, 2018 · 7 revisions

Example


HashMap hm = new HashMap();
String[] list = { “a”, “b”, “c”, “a”, “c”, “a”, “b”, “a”, “b” };

for (int i = 0; i < list.length; i++){
Integer val = (Integer) hm.get(list[i]);
if (val == null)  {
hm.put(list[i], 1);
}
else  {
hm.put(list[i], val + 1);
}
}

println(hm);

Comment
//I use a bit of “magic” of Java 1.5, which is able to automatically convert, when needed, Integer to int and back (auto-boxing).
//Note also that instead of checking if a key is there then getting it, I just get it and see if I have a result: it is simpler and faster.

by PhiLho