Home › Java Tutorial › Java HashMap and HashSet
Java HashMap and HashSet
Key-value pairs and unique values.
A HashMap stores values by key: put, get, containsKey. A HashSet keeps only unique values. A HashMap has no guaranteed order, so wrap it in a TreeMap to loop in sorted key order.
Example code
import java.util.*;
public class Main {
public static void main(String[] args) {
HashMap<String, Integer> ages = new HashMap<>();
ages.put("Ada", 36);
ages.put("Linus", 28);
System.out.println(ages.get("Ada"));
System.out.println(ages.containsKey("Bob"));
for (String k : new TreeMap<>(ages).keySet()) {
System.out.println(k + " " + ages.get(k));
}
Set<Integer> s = new HashSet<>(List.of(1, 2, 2, 3));
System.out.println(s.size());
}
}