Look things up by name
A map stores pairs: a key and its value. You look up a value by its key.
Think of it like this: A dictionary: you look up a word (the key) to find its meaning (the value). Or a phone book: name → number.
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<String, Integer> stock = new HashMap<>();
stock.put("apple", 50);
stock.put("mango", 20);
stock.put("banana", 35);
System.out.println(stock.get("mango"));
System.out.println(stock.get("grape"));
System.out.println(stock.getOrDefault("grape", 0));
System.out.println(stock.containsKey("apple"));
stock.put("apple", 45);
stock.remove("banana");
System.out.println(stock.size() + " items, apple = " + stock.get("apple"));
}
}Output
20 null 0 true 2 items, apple = 45
HashMap<String, Integer>: keys are Strings, values are Integers.putadds a pair – or replaces the value if the key already exists. Keys are unique.getgivesnullwhen the key isn't there, sogetOrDefaultis often safer.
Counting things
A classic use: count how often each word appears:
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
String[] words = "the cat and the dog and the bird".split(" ");
TreeMap<String, Integer> counts = new TreeMap<>();
for (String w : words) {
counts.put(w, counts.getOrDefault(w, 0) + 1);
}
for (String key : counts.keySet()) {
System.out.println(key + ": " + counts.get(key));
}
}
}Output
and: 2 bird: 1 cat: 1 dog: 1 the: 3
A HashMap doesn't keep any particular order. A TreeMap works the same way but keeps its keys sorted, and a LinkedHashMap keeps them in the order you added them.
Looping over keys and values together
import java.util.LinkedHashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
LinkedHashMap<String, String> capitals = new LinkedHashMap<>();
capitals.put("India", "New Delhi");
capitals.put("Japan", "Tokyo");
capitals.put("France", "Paris");
for (Map.Entry<String, String> e : capitals.entrySet()) {
System.out.println("The capital of " + e.getKey() + " is " + e.getValue());
}
}
}Output
The capital of India is New Delhi The capital of Japan is Tokyo The capital of France is Paris