beginnerFree

Map

Key-value pairs for fast lookups

Map

Maps store associations between unique keys and values, enabling fast key-based lookups (HashMap averages O(1)).

The narrated version of this skribble — tap play for the full-size video.

0:00 / 1:24

The Big Picture

The Map interface maps keys to values.

  • Implementations: HashMap, TreeMap, LinkedHashMap
  • Essential for data relationships and lookups
  • JSON objects naturally map to Map<String, Object>
  • HTTP headers, configs stored as maps

Core to Java programming - used everywhere.

How It Works

Maps keys to values using hashing or tree structures.

  • put(key, value) adds or updates entry
  • get(key) retrieves value or null
  • Iterate: entrySet(), keySet(), values()
  • Java 8+: computeIfAbsent(), merge()
  • Immutable: Map.of() (Java 9+)

In the Java Landscape

Core to Java - HTTP params, configs, caches all use maps.

  • Spring @RequestParam converts to Map
  • Properties files are key-value maps
  • EnumMap and IdentityHashMap for special cases
  • Collectors: groupingBy() produces maps from streams
  • Map.entry() (Java 9+) for creating entries

Pitfalls and Best Practices

  • Use getOrDefault() for a fallback when a key is absent
  • Hash-map keys: consistent hashCode()/equals(); TreeMap needs stable ordering
  • Avoid mutable keys
  • Use computeIfAbsent() for lazy initialization
  • Return Map.of() for immutable results
#java#collections#map