The Java collections framework is a set of interfaces — List, Set, Map, Queue — and several implementations of each. Choosing well matters, because the difference between a list and a set for a membership test is the difference between a program that finishes and one that does not. This guide covers what to use when, and the mistakes that produce runtime errors.
The four interfaces#
| Interface | Guarantees | Common implementation |
|---|---|---|
List |
ordered, duplicates allowed, index access | ArrayList |
Set |
no duplicates | HashSet |
Map |
key to value, unique keys | HashMap |
Queue |
ordered for processing | ArrayDeque |
A habit worth forming: declare the interface, construct the implementation.
List<String> names = new ArrayList<>();
Map<String, Integer> ages = new HashMap<>();
That way the rest of your code depends on the behaviour, not the implementation, and swapping it later is a one-line change.
Lists#
List<String> names = new ArrayList<>();
names.add("Ana");
names.add("Sam");
names.add(0, "Kim"); // insert at the front
names.get(1); // Ana
names.set(1, "Ana Maria");
names.remove("Sam");
names.contains("Kim"); // walks the list
names.size();
List<String> fixed = List.of("a", "b", "c"); // immutable
ArrayList or LinkedList#
| Operation | ArrayList | LinkedList |
|---|---|---|
| Get by index | instant | walks the chain |
| Add at the end | instant, amortised | instant |
| Add or remove at the front | shifts everything | instant |
| Memory per element | low | higher, node overhead |
In practice ArrayList wins nearly always, because its contiguous memory layout suits how processors read data. If you need cheap insertion at both ends, use ArrayDeque rather than LinkedList.
Sets#
Set<String> tags = new HashSet<>();
tags.add("java");
tags.add("java"); // ignored - already present
System.out.println(tags.size()); // 1
Set<String> ordered = new LinkedHashSet<>(); // keeps insertion order
Set<String> sorted = new TreeSet<>(); // keeps sorted order
The reason to reach for a set is membership testing:
List<String> blocked = loadBlockedWords(); // 50,000 entries
// Slow: checks every entry, for every message
for (String word : message) {
if (blocked.contains(word)) { }
}
// Fast: one hash lookup each
Set<String> blockedSet = new HashSet<>(blocked);
for (String word : message) {
if (blockedSet.contains(word)) { }
}
Converting the list to a set once, outside the loop, is frequently the single biggest performance improvement available in a piece of Java.
Maps#
Map<String, Integer> ages = new HashMap<>();
ages.put("Ana", 34);
ages.get("Sam"); // null if absent
ages.getOrDefault("Sam", 0); // 0 instead
ages.containsKey("Ana");
ages.putIfAbsent("Kim", 28);
// Counting
ages.merge("Ana", 1, Integer::sum);
// Grouping
Map<String, List<Order>> byCity = new HashMap<>();
byCity.computeIfAbsent(order.getCity(), k -> new ArrayList<>()).add(order);
for (Map.Entry<String, Integer> entry : ages.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
computeIfAbsent and merge replace the check-then-put pattern that fills up beginner code, and they are less error-prone.
| Map | Order | Use for |
|---|---|---|
HashMap |
none guaranteed | almost everything |
LinkedHashMap |
insertion order | when output order matters |
TreeMap |
sorted by key | ranges, sorted output |
ConcurrentHashMap |
none | shared between threads |
equals and hashCode#
This is the mistake that silently breaks sets and maps:
class Point {
int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
}
Set<Point> points = new HashSet<>();
points.add(new Point(1, 2));
points.add(new Point(1, 2));
System.out.println(points.size()); // 2 - not what you wanted
Without an override, equality is identity, so two objects with the same values are different. Implement both, always together:
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Point other)) return false;
return x == other.x && y == other.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
A record does both for you, which is the easiest correct answer:
record Point(int x, int y) { }
ConcurrentModificationException#
for (String name : names) {
if (name.startsWith("A")) {
names.remove(name); // throws
}
}
Three correct alternatives:
// 1. removeIf - clearest
names.removeIf(name -> name.startsWith("A"));
// 2. An explicit iterator
Iterator<String> it = names.iterator();
while (it.hasNext()) {
if (it.next().startsWith("A")) it.remove();
}
// 3. Build a new collection
List<String> kept = names.stream()
.filter(n -> !n.startsWith("A"))
.toList();
The same applies to maps — iterate entrySet() with an iterator, or use entrySet().removeIf(...).
Queues and deques#
Deque<String> queue = new ArrayDeque<>();
queue.addLast("first");
queue.addLast("second");
queue.pollFirst(); // "first" - FIFO
Deque<String> stack = new ArrayDeque<>();
stack.push("a");
stack.pop(); // LIFO
PriorityQueue<Task> tasks = new PriorityQueue<>(
Comparator.comparingInt(Task::priority));
Use ArrayDeque rather than the legacy Stack class, which is synchronised and slower for no benefit in single-threaded code.
Sorting#
names.sort(Comparator.naturalOrder());
names.sort(Comparator.reverseOrder());
people.sort(Comparator.comparing(Person::getSurname)
.thenComparing(Person::getFirstName));
people.sort(Comparator.comparingInt(Person::getAge).reversed());
Questions people ask#
Why is HashMap not thread-safe?
Because synchronisation costs performance that most code does not need. When several threads write to the same map, use ConcurrentHashMap rather than wrapping a HashMap.
What is the difference between Collection and Collections?
Collection is the root interface. Collections is a utility class of static helpers such as unmodifiableList and sort. The similar names are unfortunate.
Should I use streams or loops?
Whichever reads better. Streams shine for filter-map-collect chains; loops are clearer for complex logic with early exits, and marginally faster.
How do I make a collection immutable?
List.of(), Set.of() and Map.of() create immutable collections directly, and List.copyOf(existing) makes an immutable copy of one you already have.
Where to go next#
- Java basics — the syntax underneath.
- Java performance optimization — where collection choice pays.
- Advanced data structures — the ideas behind them.