Referencing a previous answer to a question on SO, there is a method used called TestForNull. This was my original code before I was told I could make it more efficient:
My original code:
for (int i = 0; i < temp.length; i++) {
if (map.containsKey(temp[i]))
map.put(temp[i], map.get(temp[i]) + 1);
else
map.put(temp[i], 1);
In this snippet, I'm doing three look-ups to the map. I was told that this could be accomplished in just one lookup, so I ended up looking for an answer on SO and found the linked answer, and modified my code to look like:
My modified code:
for (int i = 0; i < temp.length; i++) {
Integer value = map.get(temp[i]);
if (value != null)
map.put(temp[i], value + 1);
else
map.put(temp[i], 1);
}
Even though it seems better, it looks like two look-ups to me and not one. I was wondering if there was an implementation of this that only uses one, and if it can be done without the use of third-party libraries. If it helps I'm using a HashMap for my program.