Skip to content
Happy Programming Guide
Start learning
Java

Java Collections Framework

Lists, sets, maps and queues in Java: which to choose, how they differ in speed, and the mistakes that cause ConcurrentModificationException and lost data.

A backlit keyboard in a dark room

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.

JAVA
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#

JAVA
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#

JAVA
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:

JAVA
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#

JAVA
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:

JAVA
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:

JAVA
@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:

JAVA
record Point(int x, int y) { }

ConcurrentModificationException#

JAVA
for (String name : names) {
    if (name.startsWith("A")) {
        names.remove(name);        // throws
    }
}

Three correct alternatives:

JAVA
// 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#

JAVA
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#

JAVA
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 performance, where collection choice matters mostRead next

Keep reading

Java

Introduction to Java

What Java is, how the JVM works, where it is used, and your first program — plus an honest comparison with Python,…

5 min read

Java

Java Testing

Unit tests with JUnit 5: assertions, parameterised tests, mocking with Mockito, Spring Boot slice tests, and what is actually worth testing.

5 min read

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *