Coding Techniques
HashMap and TreeMap · Study material
EnumMap and immutable maps
EnumMap is the fastest map for enum keys and always iterates in declaration order. Map.of and Map.entry build small immutable maps – but do not rely on Map.of's iteration order, which can change between runs.
import java.util.EnumMap;
import java.util.Map;
enum Day { MON, TUE, WED, THU, FRI, SAT, SUN }
public class Main {
public static void main(String[] args) {
Map<Day, Integer> steps = new EnumMap<>(Day.class); // array-backed, always in enum order, very fast
steps.put(Day.SUN, 3000);
steps.put(Day.MON, 8200);
steps.put(Day.WED, 10400);
System.out.println(steps);
Map<String, Integer> codes = Map.of("IN", 91, "US", 1, "UK", 44); // immutable; order NOT guaranteed
System.out.println(codes.get("IN") + " " + codes.size());
try {
codes.put("JP", 81);
} catch (UnsupportedOperationException e) {
System.out.println("Map.of is immutable");
}
Map.Entry<String, Integer> e = Map.entry("FR", 33);
System.out.println(e.getKey() + "=" + e.getValue());
}
}
{MON=8200, WED=10400, SUN=3000}
91 3
Map.of is immutable
FR=33Safe removal and bulk updates
Map<String, Integer> stock = new HashMap<>(Map.of("pen", 0, "book", 12, "bag", 0, "lamp", 4));
stock.entrySet().removeIf(e -> e.getValue() == 0); // ✔ remove while "iterating"
stock.values().removeIf(v -> v < 5); // ✔ views write through to the map
stock.replaceAll((k, v) -> v * 2); // ✔ update every value
// ✘ for (String k : stock.keySet()) if (...) stock.remove(k); → ConcurrentModificationException Counting and grouping idioms
// count
map.merge(word, 1, Integer::sum);
// count with getOrDefault (older style)
map.put(word, map.getOrDefault(word, 0) + 1);
// group into lists
groups.computeIfAbsent(dept, d -> new ArrayList<>()).add(employee);
// group into sets
tags.computeIfAbsent(post, p -> new TreeSet<>()).add(tag);
// keep the maximum per key
best.merge(student, score, Math::max);
// invert a map (value → key); duplicate values overwrite
original.forEach((k, v) -> inverted.put(v, k)); Map checklist
- Declare as Map<K, V>; pick HashMap unless you need order.
- Use immutable keys with equals/hashCode (String, Integer, records).
- Prefer getOrDefault, merge and computeIfAbsent over null checks.
- Iterate with entrySet when you need both key and value.
- Use TreeMap for sorted output and range/nearest-key queries.
- Use LinkedHashMap for predictable order and LRU caches.
- Use ConcurrentHashMap for maps shared between threads.