Map & HashMap in Java
Store key-value pairs using HashMap, LinkedHashMap (insertion order), and TreeMap (sorted order), and learn common map operations and iteration patterns.
Map Basics
1. Creating an Empty Map
Use `HashMap` for a general-purpose key-value store with no ordering guarantee.
2. Setting a Key-Value Pair
`put(key, value)` adds or replaces an entry. If the key already exists, the old value is overwritten.
3. Checking if a Key Exists
`containsKey()` returns true if the key is present. `containsValue()` checks for a value.
4. Accessing Value on a Specific Key
`get(key)` returns the value, or `null` if not found. `getOrDefault(key, fallback)` returns a fallback instead of null.
5. Updating Value on a Specific Key
`put()` overwrites the existing value. `replace()` only updates if the key already exists.
6. Deleting a Key-Value Pair
`remove(key)` deletes the entry and returns the removed value, or `null` if not found.
7. Clearing the Map
`clear()` removes all entries. The map object still exists and can be reused.
8. Getting Map Size
`size()` returns the number of key-value pairs. `isEmpty()` returns true if the map has no entries.
Map Keys & Values
1. Getting Keys List
`keySet()` returns a `Set` of all keys. Convert to a `List` for indexed access.
2. Getting Values List
`values()` returns a `Collection` of all values. Duplicate values are included.
Traversing a Map
1. Traversing using for-each (entrySet)
`entrySet()` gives a set of `Map.Entry<K,V>` objects. Use `.getKey()` and `.getValue()` on each entry.
2. Traversing using forEach (lambda)
`forEach(BiConsumer)` is the cleanest way to iterate when you just need key and value.
3. Traversing Keys Only
Loop over `keySet()` when you only need keys, or use the key to look up the value.
Merging Maps
1. Merging Two Maps
`putAll()` copies all entries from one map into another. Duplicate keys are overwritten by the second map.
2. Merging with Conflict Strategy
`merge(key, value, remappingFunction)` lets you decide what to do when a key already exists — e.g. sum the values.
Map Variants
1. LinkedHashMap (Insertion Order)
`LinkedHashMap` preserves the order in which entries were inserted — unlike `HashMap` which has no guaranteed order.
2. TreeMap (Sorted Order)
`TreeMap` keeps entries sorted by key in natural (alphabetical / numerical) order.
3. Immutable Map (Map.of)
`Map.of()` creates a read-only map. Any attempt to add, update, or remove entries throws `UnsupportedOperationException`.