Attic
CollectionsMaps

Overview

Key-value associations, architectural isolation from Collection, and live view mechanics

Map<K, V> represents a data structure that maps unique keys to values. Unlike List or Set, Map does not implement Collection or Iterable, because its contract concerns key-value associations rather than a single sequence of items.


Map Hierarchy

ClassKey OrderingAccess / InsertNull KeyNull ValuesPrimary Application
HashMapNoneO(1) average1 allowedMultiple allowedDefault general-purpose key-value lookup
LinkedHashMapInsertion or Access orderO(1) average1 allowedMultiple allowedOrder-sensitive mapping; LRU caches
TreeMapSorted (Key ordering)O(log n)DisallowedMultiple allowedRange queries, ceiling/floor lookups

Live Collection Views

A map exposes three collection views backed directly by the map's internal data structures:

MapViews.java
Map<String, Integer> map = new HashMap<>();
map.put("Alice", 90);
map.put("Bob", 80);

// 1. Key Set View
Set<String> keys = map.keySet(); // [Alice, Bob]

// 2. Values Collection View
Collection<Integer> scores = map.values(); // [90, 80]

// 3. Entry Set View (Key + Value pairs)
Set<Map.Entry<String, Integer>> entries = map.entrySet();

// Deleting through any view immediately mutates the map!
keys.remove("Alice");
System.out.println(map.containsKey("Alice")); // false

The keySet() + get() Anti-Pattern: Never read values inside a for (String key : map.keySet()) { val = map.get(key); } loop! That pays for a second hash computation and bucket lookup for every iteration. Always iterate over map.entrySet() to receive both key and value in a single pass.


Detailed Guides

On this page