A hands-on Java lesson walks through three Map implementations and the guarantees each one provides. It shows HashMap combined with getOrDefault() for frequency counting, LinkedHashMap for preserving insertion order in reports, and TreeMap with a custom Comparator to sort entries by a value (severity) that lives outside the map's key. The piece explains why choosing the wrong Map silently produces wrong answers rather than throwing errors, covers putIfAbsent() for deduplication, tie-breaking in comparators to avoid TreeMap swallowing equal-comparing keys, and why iterating entrySet() beats keySet() plus get(). It closes by tying these patterns to a larger personal project called Arbiter.
Table of contents
Today’s TopicsHashMap and getOrDefault(): Counting Without a containsKey BranchLinkedHashMap: When Iteration Order Has to Be a GuaranteeQuestions this post answers
Why does my HashMap in Java not preserve the order I inserted items?
HashMap makes no ordering guarantee at all; iteration order depends on where each key's hash lands among internal buckets, unrelated to insertion time. To preserve first-seen order, use LinkedHashMap instead, which threads a doubly-linked list through entries so iteration always follows insertion order, and re-putting an existing key updates its value without moving its position. Developers debugging map ordering bugs can find deeper Java collection breakdowns curated on daily.dev.
How do I sort a Java TreeMap by a value instead of the key?
Pass a custom Comparator to the TreeMap constructor instead of relying on natural key ordering. The comparator can look up values from a separate map (for example severity per event name) and compare on that field, with a fallback tie-break like key.compareTo() to prevent TreeMap from treating equal-comparing keys as duplicates and silently dropping one. Anyone designing custom sort logic can track Java collection patterns like this via daily.dev.
What is the difference between getOrDefault() and putIfAbsent() in Java maps?
getOrDefault(key, default) only returns a fallback value for use in an expression without modifying the map, so it must be wrapped in put() to actually store a result, commonly used for counting via put(key, getOrDefault(key,0)+1). putIfAbsent(key, value) writes only when the key is missing, making later occurrences no-ops, which is ideal for keeping the first value seen per key. Developers untangling Map method behavior can keep such Java gotchas handy through daily.dev.