Pick the right collection for every use case.
Published January 18, 2025
The Java Collections Framework provides data structures for almost every need.
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Alice"); // duplicates allowed
System.out.println(names.get(0)); // Alice
Set<String> tags = new HashSet<>();
tags.add("java");
tags.add("java"); // second add is ignored
System.out.println(tags.size()); // 1
Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 95);
scores.put("Bob", 87);
System.out.println(scores.get("Alice")); // 95
scores.getOrDefault("Charlie", 0); // 0 — no NPE
| Need | Use | Why |
|---|---|---|
| Ordered list, allow duplicates | ArrayList | O(1) random access |
| Fast insert/delete at ends | LinkedList (as Deque) | O(1) at both ends |
| No duplicates, fast lookup | HashSet | O(1) average |
| No duplicates, sorted | TreeSet | O(log n), sorted order |
| Key-value lookup | HashMap | O(1) average |
| Key-value, sorted keys | TreeMap | O(log n), sorted |
| Key-value, insertion order | LinkedHashMap | O(1), predictable order |
For HashSet and HashMap to work correctly, your objects must implement both equals() and hashCode() consistently.
// Two objects that are equal MUST have the same hashCode
// Objects with the same hashCode may or may not be equal (hash collision)
Always know the complexity of the operations you're using. ArrayList.add(index, x) is O(n) because it shifts elements — a common gotcha.