Java Map Interface: Methods, Map.Entry and Examples - Quiz
Total: 5 questions
1. What is the difference between keySet(), values() and entrySet() in a Java Map?
What is the difference between keySet(), values() and entrySet() in a Java Map?
keySet() returns a Set<K> of keys, values() returns a Collection<V> of values (not a Set, because values may repeat), and entrySet() returns a Set<Map.Entry<K, V>> of pairs, each with getKey(), getValue() and setValue().
All three are views of the map itself, not copies: keySet().remove(key) removes the pair from the map, and entry.setValue() changes the value in place. You cannot add through a view: keySet().add() throws UnsupportedOperationException, because a new key would have no value.
When you need both the key and the value, iterate over entrySet() or call forEach((k, v) -> ...): looping over keySet() and calling get(key) inside the loop looks up every key a second time.
2. How do you tell a missing key from a key mapped to null in a Java Map?
How do you tell a missing key from a key mapped to null in a Java Map?
get(key) returns null in both cases, so its result alone cannot tell them apart. The only reliable check is containsKey(key): it returns true whenever the key is present, even if its value is null.
getOrDefault(key, defaultValue) does not help either: it returns the default only when the key is absent, and for a key mapped to null it returns null. putIfAbsent() has a similar trap: it treats a key mapped to null as absent and overwrites it.
If null values are possible, use Objects.requireNonNullElse(map.get(key), defaultValue) (Java 9) or simply do not store null in the map.
3. How do you iterate over a Java Map and safely remove entries during the iteration?
How do you iterate over a Java Map and safely remove entries during the iteration?
Use a for-each loop over entrySet() when you need both the key and the value, over keySet() or values() when you need only one of them, or the Java 8 method forEach((k, v) -> ...).
Calling map.remove(key) inside a for-each loop is a mistake: the next iterator step usually throws ConcurrentModificationException. The safe options are map.entrySet().removeIf(e -> e.getValue() < 1250), keySet().removeIf(...), values().removeIf(...) or an explicit iterator with iterator.remove(). They remove pairs through a view, and the change shows up in the map immediately.
4. How does Map.merge() work, and how do you count word frequency with it?
How does Map.merge() work, and how do you count word frequency with it?
merge(key, value, remappingFunction) was added in Java 8. If the key is absent, it stores value; if the key is present, it calls the function with the old and the new value and stores the result. If the function returns null, the pair is removed, and passing value == null throws NullPointerException.
Word frequency takes one line: counts.merge(w, 1, Integer::sum) stores 1 for a new word and adds 1 to an existing count. The naive counts.put(w, counts.get(w) + 1) fails with NullPointerException on the very first word: get() returns null, which cannot be unboxed to int.
To group values into lists, use the related method computeIfAbsent(key, k -> new ArrayList<>()).add(value).
5. What are the restrictions of maps created with Map.of(), and how do they differ from new HashMap<>()?
What are the restrictions of maps created with Map.of(), and how do they differ from new HashMap<>()?
Map.of(k1, v1, k2, v2, ...) (Java 9) creates an immutable map of up to 10 pairs; for more pairs there is Map.ofEntries(Map.entry(k, v), ...), and Map.copyOf(map) (Java 10) makes an immutable copy.
Such maps have three restrictions: any modification (put(), remove(), clear()) throws UnsupportedOperationException; a duplicate key throws IllegalArgumentException: duplicate key (duplicate values are fine); null keys and values are not allowed, and even get(null) throws NullPointerException. The iteration order is unspecified.
new HashMap<>() is mutable and allows one null key and null values. To get a mutable map with initial data, wrap the factory: new HashMap<>(Map.of(...)).