Collections: HashMap, HashSet and Deque
With ArrayList you solved many things, but there are questions for which a list is slow or awkward: how many times does each word appear in a text? Is this user already registered? What is Marta's phone number? For those cases the Java standard library (the Collections Framework) offers other structures: maps, which associate a key with a value, and sets, which do not allow duplicates. Choosing the right structure is half of the work of a good programmer.
HashMap: key and value
A Map<K, V> stores key-value pairs. Keys are unique: if you do a put with a key that already exists, you replace its value. Looking up by key with get is almost instantaneous, even with millions of entries, because HashMap uses the key's hashCode to jump straight to the right place; that is why keys must have consistent equals and hashCode (String, Integer and records already have them). get returns null if the key does not exist, and getOrDefault lets you give an alternative value. The merge method is perfect for counting: it adds one if the key exists and creates it with 1 if not. HashMap guarantees no order; if you need one, use LinkedHashMap (insertion order) or TreeMap (key order).
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
Map<String, Integer> ages = new HashMap<>();
ages.put("Ana", 30);
ages.put("Luis", 25);
ages.put("Ana", 31); // replaces the value
System.out.println(ages.get("Ana")); // 31
System.out.println(ages.get("Pedro")); // null
System.out.println(ages.getOrDefault("Pedro", 0)); // 0
System.out.println(ages.containsKey("Luis")); // true
System.out.println(ages.size()); // 2
ages.remove("Luis");
// Count words with merge
String text = "to be or not to be that is the question to be";
Map<String, Integer> counts = new TreeMap<>(); // sorted by key
for (String word : text.split(" ")) {
counts.merge(word, 1, Integer::sum);
}
System.out.println(counts);
// Iterating over entries
for (Map.Entry<String, Integer> entry : counts.entrySet()) {
if (entry.getValue() > 1) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
}
}
}HashSet and Deque
A Set<E> is a set with no duplicates: adding an element that already exists does nothing and add returns false. contains is very fast, so a HashSet is the ideal way to ask whether something is already there. It serves to remove duplicates from a list, and to do set operations: union with addAll, intersection with retainAll and difference with removeAll. TreeSet keeps elements sorted. Finally, a Deque (double-ended queue), in its ArrayDeque implementation, serves as a stack (push and pop) and as a queue (offer and poll): in a stack the last in is the first out, and in a queue the first in is the first out. Use it instead of the old Stack and Vector classes.
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
Set<String> users = new HashSet<>();
System.out.println(users.add("ana")); // true
System.out.println(users.add("ana")); // false: already there
System.out.println(users.contains("ana")); // true
List<Integer> withDuplicates = List.of(3, 1, 3, 2, 1, 5);
Set<Integer> unique = new TreeSet<>(withDuplicates);
System.out.println(unique); // [1, 2, 3, 5]
Set<Integer> a = new HashSet<>(List.of(1, 2, 3, 4));
Set<Integer> b = new HashSet<>(List.of(3, 4, 5));
Set<Integer> common = new TreeSet<>(a);
common.retainAll(b);
System.out.println(common); // [3, 4]
Deque<String> stack = new ArrayDeque<>();
stack.push("page1");
stack.push("page2");
stack.push("page3");
System.out.println(stack.pop()); // page3: last in, first out
Deque<String> queue = new ArrayDeque<>();
queue.offer("first");
queue.offer("second");
System.out.println(queue.poll()); // first: first in, first out
System.out.println(queue.peek()); // second: look without removing
// Balanced parentheses with a stack
String expr = "(a + (b * c))";
Deque<Character> open = new ArrayDeque<>();
boolean balanced = true;
for (char c : expr.toCharArray()) {
if (c == '(') open.push(c);
else if (c == ')') {
if (open.isEmpty()) { balanced = false; break; }
open.pop();
}
}
System.out.println(balanced && open.isEmpty()); // true
}
}- List: ordered, allows duplicates, access by position (ArrayList).
- Set: no duplicates; HashSet (no order, fast), LinkedHashSet (insertion order), TreeSet (sorted).
- Map: unique key -> value; HashMap, LinkedHashMap, TreeMap.
- Deque: stack and queue with ArrayDeque.
- If you use your classes as a map key or inside a set, override equals and hashCode (or use a record).
- Mutating an object that is already a map key breaks lookup: use immutable keys.
Testez vos acquis
Question 1 sur 1What happens when you put a key that already exists in a HashMap?
✎ Mes notes
Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères