Maps
A Map associates unique keys with values. Language names can be keys and file extensions can be values.
Putting a value for an existing key replaces the previous mapping. A map models lookup by key rather than a sequence position.
Look up a value by key
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, String> extensions = new HashMap<>();
extensions.put("Java", ".java");
extensions.put("Python", ".pyc");
extensions.replace("Python", ".py");
System.out.println(extensions.get("Python"));
System.out.println(
extensions.getOrDefault("Go", "Unknown"));
}
}
Output:
.py
Unknown
put stores a mapping under a key, and replace swaps the value for a key that already exists. get finds the extension stored under Python, while getOrDefault supplies a useful fallback when Go is not a key.
HashMap is the everyday implementation and promises nothing about order; LinkedHashMap also remembers insertion order, which keeps printed maps predictable. get returns null for a missing key, while containsKey checks whether the key exists.
Add two fruit counts, update pears, and read the count stored for apples.