← Java from Scratch Lesson 76 of 88 · 10 XP

Map

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

Map<K, V> is a dictionary: each key has one value.

Map<String, Integer> age = new HashMap<>();
age.put("Kai", 25);
age.put("Kai", 26);                 // the key is the same — the value is replaced
age.get("Kai")                      // 26
age.get("Bob")                      // null — there's no such key
age.getOrDefault("Bob", 0)          // 0
age.containsKey("Kai")
age.remove("Kai");
age.putIfAbsent("Ann", 30);
for (Map.Entry<String, Integer> e : age.entrySet())
    System.out.println(e.getKey() + " = " + e.getValue());
age.keySet(), age.values()

A Map isn't a Collection: it holds pairs. The keys are unique (like a Set), and the values can repeat.

Task. A phone book. Commands: add name number (replace it if it was there and print updated, otherwise added), get name (the number or not found), del name (deleted / not found), count.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.