Task 7 of 9 · 0 solved · 9 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

10.1 HashMap — walking key and value together

Lesson

Обход через keySet делает лишнюю работу

Looping over keySet() and calling get(key) means Java searches the map twice for every entry: once to hand you the key, once to look up its value. For small maps nobody notices, but there is a cleaner way.


entrySet — сразу пара

for (Map.Entry<String, Integer> e : counts.entrySet()) {
    System.out.println(e.getKey() + " = " + e.getValue());
}

Each Map.Entry is one key-value pair; getKey() and getValue() read it without another lookup. The type looks long, but the pattern is always the same.

Use keySet() when only the keys matter, and entrySet() when you need both.


▶ Try it: run this, then change something and run it again.



Each Map.Entry holds...


Why is entrySet better than keySet plus get?


Type exactly what this program prints.

import java.util.Map;
import java.util.TreeMap;

public class Main { public static void main(String[] a){
    Map<String, Integer> m = new TreeMap<String, Integer>();
    m.put("b", 2);
    m.put("a", 1);
    for (Map.Entry<String, Integer> e : m.entrySet()) {
        System.out.println(e.getKey() + ":" + e.getValue());
    }
}}

When is keySet still the right choice?


True or false?