Java Map Views and Special Maps: LinkedHashMap, EnumMap, WeakHashMap and IdentityHashMap
Master Java map views (keySet, values, entrySet) and Map.Entry, then the specialized maps and sets: LinkedHashMap with access order and an LRU cache, SequencedMap, EnumSet and EnumMap, IdentityHashMap, and WeakHashMap with its garbage-collector tricks.
kvi5hnuCode Sprout team member12 min readOn this page
Article 87 covered the everyday map operations. This one goes deeper in two directions. First, views: a map is not itself a Collection, but it hands out collection objects that look into it, and those views let you iterate over a map and edit it in bulk. Second, the specialized maps and sets in java.util. LinkedHashMap gives predictable order and a ready-made LRU cache. EnumSet and EnumMap are the fastest options for enum keys. IdentityHashMap compares keys with ==, and WeakHashMap lets the garbage collector clean up entries.
Map views: keySet, values and entrySet
The collections framework doesn't treat a map as a collection. Some other libraries model a map as a "collection of pairs", but Java keeps the two hierarchies separate. Instead, a map provides three views: objects that implement a collection interface and are backed by the map itself.
Set<K> keySet()
Collection<V> values()
Set<Map.Entry<K, V>> entrySet()
The key set and entry set are Sets because keys are unique. The values view is a plain Collection, because two keys may map to the same value. None of these is a HashSet or TreeSet copy. Each one is a lightweight object that reads straight from the map, so creating a view costs O(1), and later changes to the map show up in it.
To loop over keys:
for (String key : map.keySet()) { ... }
When you need keys and values, iterate over the entries. That avoids a second lookup per key:
for (Map.Entry<String, Integer> entry : counts.entrySet()) {
String k = entry.getKey();
Integer v = entry.getValue();
...
}
for (var entry : map.entrySet()) saves you from typing the Map.Entry<…> type. map.forEach((k, v) -> …) is even shorter when you don't need to modify anything.
What you can and can't do through a view
- Remove: yes. Removing from any view removes the whole entry from the map. That includes
keySet().remove(k),values().remove(v)(the first entry with that value), iteratorremove,removeIfandretainAll.map.values().removeIf(v -> v == 0)deletes every zero entry in one line, andmap.keySet().retainAll(allowed)keeps only the allowed keys. - Add: no.
keySet().add(k)throwsUnsupportedOperationException, because a key without a value makes no sense. The entry set refusesaddas well, even though adding a pair would be meaningful. - Update values: yes, through entries. The entries of
entrySet()are live.entry.setValue(v)writes into the map, and if the map changes some other way, the entry sees the new value.
The usual fail-fast rules apply. Modifying the map directly (not through the iterator) while iterating over a view causes ConcurrentModificationException.
LinkedHashMap and LinkedHashSet: predictable order
A hash table's iteration order looks random. LinkedHashMap and LinkedHashSet fix that. They are ordinary hash tables in which every entry is also linked into a doubly linked list. Lookups use the buckets as usual, and iteration follows the list.

By default the list is in insertion order. Putting an existing key again replaces the value but keeps its position. The extra cost is two references per entry, and iteration is actually a little faster than with HashMap, because it walks only the entries instead of every bucket. When you want hash-table speed with reproducible output (logs, JSON, tests, configuration listings), LinkedHashMap is the easy choice.
Access order and LRU caches
Pass true as the third constructor argument, and the list follows access order instead. Every get or put moves the touched entry to the tail of the list. Only the list position changes; the entry stays in its hash bucket. The head of the list is then always the least recently used entry.
Combine that with the removeEldestEntry hook, which the map calls after every insertion, and you have a complete LRU cache:
class LruCache<K, V> extends LinkedHashMap<K, V> {
private final int capacity;
LruCache(int capacity) {
super(16, 0.75f, true); // access order
this.capacity = capacity;
}
@Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity; // evict the least recently used entry
}
}
removeEldestEntry receives the eldest entry, so the decision can depend on it, for example evicting only entries whose timestamp is old enough. Because it runs only once per insertion, it removes at most one entry automatically. If you want to evict several old entries, remove them yourself inside the method and return false.
SequencedMap (Java 21)
LinkedHashMap (along with TreeMap) implements the Java 21 SequencedMap interface, and LinkedHashSet implements SequencedSet. That gives a uniform API for both ends:
firstEntry(),lastEntry(),pollFirstEntry()andpollLastEntry()putFirst(k, v)andputLast(k, v), which move or insert the entry at an end (on aLinkedHashMap)reversed(), a reverse-order view, plussequencedKeySet(),sequencedValues()andsequencedEntrySet()
LinkedHashMap.newLinkedHashMap(n) and LinkedHashSet.newLinkedHashSet(n) (Java 19) create pre-sized instances, like HashMap.newHashMap.
EnumSet and EnumMap
When the elements or keys are enum constants, java.util has implementations that beat hashing by a wide margin.
EnumSet is a bit vector. Bit i is on when the constant with ordinal i is present. For enums with up to 64 constants, the whole set is a single long, so contains, add and set operations like addAll become one or two bitwise instructions. It has no public constructors; you use static factories:
enum Weekday { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
EnumSet<Weekday> always = EnumSet.allOf(Weekday.class);
EnumSet<Weekday> never = EnumSet.noneOf(Weekday.class);
EnumSet<Weekday> workday = EnumSet.range(Weekday.MONDAY, Weekday.FRIDAY);
EnumSet<Weekday> mwf = EnumSet.of(Weekday.MONDAY, Weekday.WEDNESDAY, Weekday.FRIDAY);
EnumSet<Weekday> weekend = EnumSet.complementOf(workday);
The resulting sets are mutable, iterate in declaration order, and reject null. EnumSet is the idiomatic replacement for bit-flag int constants (READ | WRITE | EXECUTE). You get type safety and readable toString output at the same speed.
EnumMap is a map with enum keys, implemented as a plain array of values indexed by ordinal. You pass the key's class to the constructor, because erasure hides it otherwise:
var personInCharge = new EnumMap<Weekday, Employee>(Weekday.class);
It also iterates in declaration order, whatever order you inserted in.
IdentityHashMap
IdentityHashMap breaks the normal map contract on purpose. It hashes keys with System.identityHashCode, the value Object.hashCode would return based on the object's identity, even if the class overrides hashCode. It compares keys with == instead of equals. Two distinct key objects are different keys even when their contents are equal.
That is exactly what graph-traversal algorithms need: serialization, deep copying, object-graph printing, cycle detection. They have to remember "have I visited this particular object?", and two equal-but-distinct objects must both be visited. Collections.newSetFromMap(new IdentityHashMap<>()) gives an identity-based set.
Internally, IdentityHashMap uses open addressing in one flat array instead of buckets with chains. Its constructor takes an expected maximum size rather than a capacity.
WeakHashMap
Imagine a long-lived map that associates extra data with objects, such as metadata for UI components or computed results for request objects. When the rest of the program stops using a key object, nobody can ever look up its entry again. The garbage collector still can't reclaim it, though, because the map itself is reachable and holds strong references to all its keys. The result is a classic memory leak.
WeakHashMap cooperates with the garbage collector to avoid this. It holds its keys through WeakReference objects. If the only remaining references to a key are weak ones, the collector reclaims the key and puts the weak reference onto a reference queue. The WeakHashMap checks that queue during its normal operations and removes the entries whose keys are gone.
Map<Widget, Metadata> extra = new WeakHashMap<>();
extra.put(widget, meta);
widget = null; // after a GC, the entry may disappear
Several details trip people up:
- The values are strong. If a value refers back to its own key, the key stays reachable and the entry never goes away.
- String literals and small boxed
Integers are poor keys. Literals are interned and cached boxes are reused, so they stay reachable forever. - Keys are compared with
equals, but collection depends on identity.WeakHashMapmakes the most sense for keys that use identity equality. - It is not a cache. Weakly reachable objects are cleared at the next collection, often almost immediately. For memory-sensitive caches,
SoftReferenceor a caching library is the better tool. Entries also vanish at unpredictable times, sosize()can change between two calls even if your program doesn't touch the map.
A complete example
The program exercises views, live and copied entries, insertion versus hash order, SequencedMap methods, the LRU cache, EnumSet and EnumMap, and identity keys. WeakHashMap is left out because garbage collection timing isn't deterministic.
import java.util.*;
public class Solution {
enum Weekday { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
// an LRU cache in a few lines
static class LruCache<K, V> extends LinkedHashMap<K, V> {
private static final long serialVersionUID = 1L;
private final int capacity;
LruCache(int capacity) {
super(16, 0.75f, true); // true = access order
this.capacity = capacity;
}
@Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity;
}
}
public static void main(String[] args) {
// 1. the three views of a map
Map<String, Integer> counts = new TreeMap<>(Map.of("ant", 3, "bee", 7, "cat", 1, "dog", 4));
Set<String> keys = counts.keySet();
Collection<Integer> values = counts.values();
Set<Map.Entry<String, Integer>> entries = counts.entrySet();
System.out.println("keys " + keys + ", values " + values + ", entries " + entries);
for (Map.Entry<String, Integer> entry : entries)
entry.setValue(entry.getValue() * 10); // writes through to the map
System.out.println("after setValue: " + counts);
keys.remove("ant"); // removes the entry from the map
values.remove(10); // removes cat=10
entries.removeIf(e -> e.getValue() > 60); // removes bee=70
System.out.println("after removing through views: " + counts);
counts.put("eel", 2);
System.out.println("views are live: keys now " + keys);
try {
keys.add("fox");
} catch (UnsupportedOperationException e) {
System.out.println("keySet().add: UnsupportedOperationException");
}
// live entries vs detached copies
Map.Entry<String, Integer> live = counts.entrySet().iterator().next();
Map.Entry<String, Integer> copy = Map.Entry.copyOf(live);
counts.put("dog", 99);
System.out.println("live entry " + live + ", copy " + copy + ", Map.entry pair " + Map.entry("x", 1));
// 2. LinkedHashMap keeps insertion order
var hash = new HashMap<String, String>();
var linked = new LinkedHashMap<String, String>();
for (String id : List.of("E-503", "E-118", "E-972", "E-260")) {
hash.put(id, "?");
linked.put(id, "?");
}
System.out.println("HashMap keys " + hash.keySet() + ", LinkedHashMap keys " + linked.keySet());
// SequencedMap (Java 21) methods
linked.putFirst("E-001", "boss");
linked.putLast("E-999", "intern");
System.out.println("firstEntry " + linked.firstEntry() + ", lastEntry " + linked.lastEntry()
+ ", reversed keys " + linked.reversed().keySet());
// 3. access order and an LRU cache
var cache = new LruCache<String, String>(3);
cache.put("a", "A");
cache.put("b", "B");
cache.put("c", "C");
cache.get("a"); // touch a: now most recently used
cache.put("d", "D"); // evicts the least recently used: b
System.out.println("LRU cache " + cache.keySet());
// 4. EnumSet and EnumMap
EnumSet<Weekday> always = EnumSet.allOf(Weekday.class);
EnumSet<Weekday> never = EnumSet.noneOf(Weekday.class);
EnumSet<Weekday> workday = EnumSet.range(Weekday.MONDAY, Weekday.FRIDAY);
EnumSet<Weekday> mwf = EnumSet.of(Weekday.MONDAY, Weekday.WEDNESDAY, Weekday.FRIDAY);
System.out.println(always.size() + " days, never " + never + ", weekend " + EnumSet.complementOf(workday));
System.out.println("mwf " + mwf + ", workday contains SATURDAY? " + workday.contains(Weekday.SATURDAY));
var personInCharge = new EnumMap<Weekday, String>(Weekday.class);
personInCharge.put(Weekday.FRIDAY, "Lena");
personInCharge.put(Weekday.MONDAY, "Priya");
personInCharge.put(Weekday.WEDNESDAY, "Tom");
System.out.println("EnumMap (declaration order) " + personInCharge);
// 5. IdentityHashMap compares keys with ==
String k1 = new String("key");
String k2 = new String("key");
Map<String, Integer> byEquals = new HashMap<>();
Map<String, Integer> byIdentity = new IdentityHashMap<>();
for (String k : List.of(k1, k2)) {
byEquals.merge(k, 1, Integer::sum);
byIdentity.merge(k, 1, Integer::sum);
}
System.out.println("HashMap size " + byEquals.size() + ", IdentityHashMap size " + byIdentity.size());
System.out.println("k1.hashCode() == k2.hashCode(): " + (k1.hashCode() == k2.hashCode()));
}
}
keys [ant, bee, cat, dog], values [3, 7, 1, 4], entries [ant=3, bee=7, cat=1, dog=4]
after setValue: {ant=30, bee=70, cat=10, dog=40}
after removing through views: {dog=40}
views are live: keys now [dog, eel]
keySet().add: UnsupportedOperationException
live entry dog=99, copy dog=40, Map.entry pair x=1
HashMap keys [E-503, E-118, E-260, E-972], LinkedHashMap keys [E-503, E-118, E-972, E-260]
firstEntry E-001=boss, lastEntry E-999=intern, reversed keys [E-999, E-260, E-972, E-118, E-503, E-001]
LRU cache [c, a, d]
7 days, never [], weekend [SATURDAY, SUNDAY]
mwf [MONDAY, WEDNESDAY, FRIDAY], workday contains SATURDAY? false
EnumMap (declaration order) {MONDAY=Priya, WEDNESDAY=Tom, FRIDAY=Lena}
HashMap size 1, IdentityHashMap size 2
k1.hashCode() == k2.hashCode(): true
In the LRU line, b was evicted rather than a, because get("a") moved a to the most recently used end. In the identity test, the two "key" strings have equal contents and equal hash codes, so HashMap sees one key, while IdentityHashMap sees two distinct objects.
Common questions
What is the fastest way to loop over a map's keys and values?
Loop over entrySet() or call map.forEach((k, v) -> ...). Looping over keySet() and calling get for each key does a second lookup every time.
How do I remove entries while iterating?
Through the views: map.entrySet().removeIf(e -> ...) or map.values().removeIf(...), or iterator.remove() on a view's iterator. Calling map.remove inside a for-each loop throws ConcurrentModificationException.
How do I keep the order in which keys were inserted?
Use LinkedHashMap (or LinkedHashSet). It costs a little memory per entry and keeps hash-table speed. Since Java 21, it also has firstEntry, lastEntry, putFirst, putLast and reversed.
Is a LinkedHashMap LRU cache good enough for production?
For small, single-threaded caches, yes. It isn't thread-safe, and even get changes the structure in access-order mode. For shared caches with expiry and statistics, use a library such as Caffeine.
When should I use WeakHashMap?
For attaching extra data to objects you don't own, where the entry should disappear when the object itself is no longer used. It isn't a cache: entries can vanish at the next garbage collection, and values that reference their own keys keep the entries alive forever.
API reference
java.util.Map<K, V> (views)
| Method | Description |
|---|---|
Set<Map.Entry<K, V>> entrySet() | set view of the entries; supports removal but not addition |
Set<K> keySet() | set view of the keys; removing a key removes its entry |
Collection<V> values() | collection view of the values; removing a value removes its entry |
java.util.Map.Entry<K, V>
| Method | Description |
|---|---|
K getKey(), V getValue() | the key or value of the entry |
V setValue(V newValue) | writes the new value into the map, returns the old value |
static <K, V> Map.Entry<K, V> copyOf(Map.Entry<? extends K, ? extends V> e) (Java 17) | detached, immutable copy |
Map.entry(K k, V v) (on Map, Java 9) | new immutable entry, not tied to any map |
java.util.LinkedHashMap<K, V> and java.util.LinkedHashSet<E>
| Method | Description |
|---|---|
LinkedHashMap(), LinkedHashMap(int initialCapacity), LinkedHashMap(int initialCapacity, float loadFactor) | empty map in insertion order |
LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) | true for access order, false for insertion order |
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) | called after each insertion; return true to remove eldest (default false) |
LinkedHashSet(), LinkedHashSet(int initialCapacity), LinkedHashSet(int initialCapacity, float loadFactor) | empty set in insertion order |
java.util.EnumSet<E extends Enum<E>>
| Method | Description |
|---|---|
allOf(Class<E> type), noneOf(Class<E> type) | all constants, or empty (mutable) |
range(E from, E to) | constants from from to to, inclusive |
of(E e), …, of(E first, E... rest) | the given constants (no null) |
complementOf(EnumSet<E> s) | all constants not in s |
copyOf(EnumSet<E> s), copyOf(Collection<E> c) | mutable copy (c must be an EnumSet or non-empty) |
Other classes
| Method | Description |
|---|---|
EnumMap(Class<K> keyType) | empty map with keys of the given enum type |
IdentityHashMap(), IdentityHashMap(int expectedMaxSize) | empty identity map (default expected size 21) |
WeakHashMap(), WeakHashMap(int initialCapacity), WeakHashMap(int initialCapacity, float loadFactor) | empty map with weakly referenced keys |
static int System.identityHashCode(Object obj) | identity-based hash code, even if hashCode is overridden |
Summary
keySet,valuesandentrySetare live views. They support removal (includingremoveIfandretainAll), not addition. EntrysetValuewrites through to the map.- Use
Map.Entry.copyOffor snapshots andMap.entryfor standalone pairs. LinkedHashMapandLinkedHashSetgive insertion order. Access-order mode plusremoveEldestEntrymakes an LRU cache. Both implement Java 21's sequenced interfaces.EnumSet(a bit vector) andEnumMap(an array) are the fastest sets and maps for enum elements, and they iterate in declaration order.IdentityHashMapuses==and identity hash codes, which suits object-graph traversals.WeakHashMapdrops entries whose keys are no longer strongly reachable. Beware of strong values that point back to keys, and don't use it as a cache.
Practice Questions
How do you remove all entries whose value is 0 from a Map<String, Integer> in one statement?
map.values().removeIf(v -> v == 0);. Removing from the values view removes the corresponding entries. The form map.entrySet().removeIf(e -> e.getValue() == 0) works too.
Why does map.keySet().add("x") throw an exception?
Adding a key without a value can't be expressed in the map, so key set views reject add with UnsupportedOperationException. Use map.put("x", value) instead.
A LinkedHashMap in access order has keys a, b, c (a is eldest). You call get("a"), then put("b", ...). What is the iteration order now?
c, a, b. Each access moves the touched entry to the tail: get("a") gives b, c, a, and then put("b", …) gives c, a, b.
Why is EnumSet faster than HashSet<Weekday>?
It stores membership as bits in a long (or a long[] for large enums), indexed by ordinal. There is no hashing, no entry object and no equals call, and bulk operations are bitwise AND and OR.
An entry in a WeakHashMap never disappears even though the key is unused elsewhere. What is a likely cause?
The value holds a strong reference to the key, directly or indirectly, so the key stays strongly reachable through the map's own value. Another cause is a key that is a string literal or a cached boxed value, which is always reachable.
Previous: Java Maps: HashMap, TreeMap and Updating Map Entries
Next: Java Collection Copies and Views: Immutable Collections, Subranges and Unmodifiable Views
Related reading
- Java Maps: HashMap, TreeMap and Updating Map Entries
- Java Queues and Deques: ArrayDeque, LinkedList and PriorityQueue
- Java HashSet and TreeSet: Hash Tables, Hash Codes and Sorted Sets
- Java LinkedList vs ArrayList: Linked Lists, ListIterator and Array Lists
- Java Collection Interfaces: List, Set, Queue, Map and Sequenced Collections

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.