Video in progress

Strong Middle 🧺 Collections

Can you keep a Map.Entry taken from entrySet() to use later? How does it differ from Map.entry() and AbstractMap.SimpleEntry?

Better not to: in HashMap the entry is the internal node itself and changes when the Map changes, TreeMap.firstEntry() gives an immutable snapshot, and other Maps behave differently again. If you need a pair, create an independent object with Map.entry(k, v) or a record.

📖 Answer

The HashMap.entrySet() iterator hands out the internal Node objects themselves. They are "live":

Map.Entry<String, Integer> saved = null;
for (var e : prices.entrySet()) {
    if (e.getKey().equals("olma")) saved = e;
}
prices.put("olma", 99);
saved.getValue();   // 99 — this is not a copy, it is the node inside the Map
prices.remove("olma");
saved.setValue(1);  // no error, but it has no effect on the Map

Other Maps behave differently, and you will be surprised if you don't know it:

  • navigation methods like TreeMap.firstEntry() and floorEntry() return an immutable snapshot, and setValue throws UnsupportedOperationException;
  • the iterators of IdentityHashMap and EnumMap hand out the entry as a window tied to the iterator's state; using it after the element has been removed can throw IllegalStateException;
  • a ConcurrentHashMap entry is a copy made during iteration: setValue does a put to the Map, but the entry doesn't see changes other threads make afterwards.

So an entry is a tool for the moment of iteration. Don't keep it in a field or a cache, and don't pass it to another thread.

If you need an independent pair:

null mutation
Map.entry(k, v) (Java 9+) no no
new AbstractMap.SimpleImmutableEntry<>(k, v) yes no
new AbstractMap.SimpleEntry<>(k, v) yes has setValue

In a stream, Map.entry is handy for an intermediate result: .map(e -> Map.entry(e.getKey(), convert(e.getValue()))). In domain code, record SkuQty(String sku, int qty) is clearer: named fields say more than getKey()/getValue().