Skip to content

Maps: look up by key

Read · 1 of 4

A map links keys to values

Map<String, Integer> count = new HashMap<>(); maps words to numbers. count.put(key, value) stores, count.get(key) reads, count.containsKey(key) checks.

count.getOrDefault(key, 0) gives 0 when the key isn't there yet, so count.put(w, count.getOrDefault(w, 0) + 1) counts in one line.

A HashMap is fastest but keeps keys in no particular order. A TreeMap keeps them sorted.