DEV Community

Cover image for How to choose Java collection types: List, Set, Map
duong vu
duong vu

Posted on Originally published at shippedcode.dev

How to choose Java collection types: List, Set, Map

Originally published at Shipped Code.

Most backend Java code gets by with ArrayList and HashMap, until a method returns a list nobody can add to or a loop throws ConcurrentModificationException. How you choose a Java collection comes down to 3 questions. Do you need duplicates and positions? Use a List (ArrayList by default). Do you need uniqueness? Use a Set (HashSet, or LinkedHashSet to keep insertion order, TreeSet to keep it sorted). Do you look things up by key? Use a Map (HashMap, or LinkedHashMap/TreeMap when order matters).

Return List.copyOf(...) from methods so callers cannot change your data, keep LinkedList for the rare case you have measured, and switch to ConcurrentHashMap once several threads write to the same map. The classic trap is removing elements inside a for-each loop, and removeIf fixes it.

This post is for developers who write Java every day. If you are here for a specific exception, jump to Common traps.

Decision table

Need Pick Main trade-off
Ordered items, duplicates allowed, access by index ArrayList Inserting or removing in the middle shifts the elements after it
A fixed list you hand to callers List.of / List.copyOf Throws on any change, rejects null
Unique values, order irrelevant HashSet Iteration order looks random
Unique values in the order they arrived LinkedHashSet A bit more memory than HashSet
Unique values, sorted, range queries TreeSet O(log n) instead of O(1)
Lookup by key HashMap No order; not thread-safe
Lookup by key, keep insertion order LinkedHashMap A bit more memory than HashMap
Lookup by key, sorted, "next key after X" TreeMap O(log n); keys must be comparable
A map shared between threads ConcurrentHashMap No null keys or values

The Java backend roadmap puts collections in stage 1, modern core Java, and lists what to learn next.

Blocks titled Main.java are complete files that run with java Main.java on JDK 21.0.11. The others are excerpts that need imports and a main method.

Lists

ArrayList is the right default for nearly every list in a backend, such as DTOs for a response, rows from a query or items in a cart. It stores elements in one array, so reading by index is O(1), and iterating walks one contiguous block of references.

LinkedList looks better on paper for inserts in the middle, but you first have to walk to that position node by node, and each node is a separate object scattered across the heap. For typical backend lists it rarely beats ArrayList, and this post does not try to prove that with timings. The one job it does well is a queue, and ArrayDeque does that job too, without the per-node objects.

The interesting choice is how to make a list read-only. Java gives you 4 ways, and they behave differently.

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<String> source = new ArrayList<>(List.of("a", "b"));

        List<String> view = Collections.unmodifiableList(source);
        List<String> copy = List.copyOf(source);
        source.add("c");

        System.out.println("view = " + view);   // sees the new element
        System.out.println("copy = " + copy);   // snapshot

        List<String> fixed = Arrays.asList("x", "y");
        fixed.set(0, "z");                      // allowed
        System.out.println("fixed = " + fixed);

        try {
            copy.add("d");
        } catch (UnsupportedOperationException e) {
            System.out.println("copy.add -> " + e);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
view = [a, b, c]
copy = [a, b]
fixed = [z, y]
copy.add -> java.lang.UnsupportedOperationException
Enter fullscreen mode Exit fullscreen mode

The view changed after it was created, because Collections.unmodifiableList only blocks writes through the wrapper. Anyone holding source can still change what your caller sees. List.copyOf takes a snapshot, and List.of builds an immutable list from values. Arrays.asList is the odd one, because you can replace elements but cannot add or remove them. The last line shows copy.add failing with an empty exception message, which makes the error hard to search for.

For a method that returns a list, return List.copyOf(items); is the safe default, as long as the list holds no null (see Common traps).

Sets

A common use for a Set in a backend is cleaning up ids from a request, for example ?ids=42,7,42,19,7. All 3 implementations remove the duplicates. They differ only in the order you get back.

List<Long> requested = List.of(42L, 7L, 42L, 19L, 7L);

System.out.println("HashSet       " + new HashSet<>(requested));
System.out.println("LinkedHashSet " + new LinkedHashSet<>(requested));
System.out.println("TreeSet       " + new TreeSet<>(requested));
Enter fullscreen mode Exit fullscreen mode
HashSet       [19, 7, 42]
LinkedHashSet [42, 7, 19]
TreeSet       [7, 19, 42]
Enter fullscreen mode Exit fullscreen mode

The HashSet order comes from hash buckets, and the specification does not promise it. If those ids end up in a JSON response or a cache key, use LinkedHashSet so the output is stable and matches what the client sent. Use TreeSet when the result should be sorted anyway.

Hash-based sets decide "same element" with equals and hashCode. A record generates both from its fields, so 2 records with the same values count as one. A plain class without those methods compares by identity.

record SkuKey(String sku, String warehouse) {}

static class SkuClass {             // no equals/hashCode
    final String sku, warehouse;
    SkuClass(String sku, String warehouse) { this.sku = sku; this.warehouse = warehouse; }
}

// add new SkuKey("TSHIRT-M", "HN") twice to one HashSet, then SkuClass twice to another
Enter fullscreen mode Exit fullscreen mode
records: 1
plain class: 2
Enter fullscreen mode Exit fullscreen mode

That second line is how duplicate rows sneak into a "unique" set. Records are the simplest fix for composite keys like this one.

For JPA users, entity collections (Set versus List in Hibernate) have their own rules, which the post on N+1 queries covers.

Maps

The most common map in a service is a lookup by id. You build it once from a list, then each get is O(1) instead of a scan through the list.

import java.util.*;

public class Main {
    record User(long id, String name, String team) {}

    public static void main(String[] args) {
        List<User> users = List.of(
            new User(1, "An", "mobile"),
            new User(2, "Binh", "backend"),
            new User(3, "Chi", "mobile"));

        Map<Long, User> byId = new HashMap<>();
        for (User u : users) byId.put(u.id(), u);
        System.out.println(byId.get(2L).name());
        System.out.println(byId.getOrDefault(99L, new User(0, "unknown", "-")).name());

        Map<String, List<String>> byTeam = new LinkedHashMap<>();
        for (User u : users) {
            byTeam.computeIfAbsent(u.team(), t -> new ArrayList<>()).add(u.name());
        }
        System.out.println(byTeam);
    }
}
Enter fullscreen mode Exit fullscreen mode
Binh
unknown
{mobile=[An, Chi], backend=[Binh]}
Enter fullscreen mode Exit fullscreen mode

computeIfAbsent creates the list the first time a team appears and returns the existing list after that, which replaces the usual if (!map.containsKey(...)) block. The grouping map is a LinkedHashMap, so teams come out in the order they first appeared. Streams can do the same with Collectors.toMap and groupingBy; the next post in this series covers them.

Reach for TreeMap when the question is "what is the next key after X?". Free appointment slots are a good example.

TreeMap<LocalTime, String> slots = new TreeMap<>();
slots.put(LocalTime.of(9, 0), "room 1");
slots.put(LocalTime.of(10, 30), "room 2");
slots.put(LocalTime.of(14, 0), "room 1");
slots.put(LocalTime.of(16, 15), "room 3");

LocalTime now = LocalTime.of(10, 5);
System.out.println("next slot:   " + slots.ceilingKey(now));
System.out.println("before noon: " + slots.headMap(LocalTime.NOON));
System.out.println("from 14:00:  " + slots.tailMap(LocalTime.of(14, 0), true));
Enter fullscreen mode Exit fullscreen mode
next slot:   10:30
before noon: {09:00=room 1, 10:30=room 2}
from 14:00:  {14:00=room 1, 16:15=room 3}
Enter fullscreen mode Exit fullscreen mode

With a HashMap you would sort the keys or scan all of them for each of these questions. headMap excludes its bound by default, while tailMap(key, true) includes it.

For enum keys, EnumMap and EnumSet are worth knowing. They are backed by an array or a bit vector indexed by the enum's ordinal, and they iterate in declaration order.

Sequenced collections (Java 21)

Java 21 added SequencedCollection and SequencedMap (JEP 431). They give every ordered collection the same methods for the first and last element. That covers List, Deque, LinkedHashSet, TreeSet, LinkedHashMap and TreeMap.

List<String> events = new ArrayList<>(List.of("created", "paid", "shipped"));
System.out.println(events.getFirst() + " .. " + events.getLast());
System.out.println(events.reversed());

SequencedSet<Long> recentIds = new LinkedHashSet<>(List.of(42L, 7L, 19L));
System.out.println(recentIds.getLast() + " " + recentIds.reversed());

SequencedMap<String, Integer> steps = new LinkedHashMap<>();
steps.put("validate", 1);
steps.put("charge", 2);
steps.put("notify", 3);
System.out.println(steps.firstEntry() + " " + steps.lastEntry());
System.out.println(steps.pollFirstEntry() + " -> " + steps);
Enter fullscreen mode Exit fullscreen mode
created .. shipped
[shipped, paid, created]
19 [19, 7, 42]
validate=1 notify=3
validate=1 -> {charge=2, notify=3}
Enter fullscreen mode Exit fullscreen mode

Before Java 21, the last element of a LinkedHashSet meant iterating the whole set. reversed() returns a view, not a copy, and it keeps the original's rules, so calling removeFirst() on List.of("a", "b").reversed() still throws UnsupportedOperationException. I compiled the same file with JDK 17 to check the floor, and it fails with cannot find symbol ... method getFirst().

Sharing a collection between threads (Advanced)

You can skip this section if your collections live inside one request. HashMap is not thread-safe, and when several threads write to it the failure is usually silent. Here, 8 threads each count 100,000 hits into one map.

import java.util.*;
import java.util.concurrent.*;

public class Main {
    static int count(Map<String, Integer> hits) throws Exception {
        try (ExecutorService pool = Executors.newFixedThreadPool(8)) {
            for (int t = 0; t < 8; t++) {
                pool.submit(() -> {
                    for (int i = 0; i < 100_000; i++) hits.merge("GET /users", 1, Integer::sum);
                });
            }
        } // close() waits for all tasks
        return hits.get("GET /users");
    }

    public static void main(String[] args) throws Exception {
        System.out.println("expected          800000");
        System.out.println("HashMap           " + count(new HashMap<>()));
        System.out.println("ConcurrentHashMap " + count(new ConcurrentHashMap<>()));
    }
}
Enter fullscreen mode Exit fullscreen mode
expected          800000
HashMap           139374
ConcurrentHashMap 800000
Enter fullscreen mode Exit fullscreen mode

The HashMap number changed on every run. Across 13 runs it landed between 126,637 and 367,392, never close to 800,000. My first suspicion was that some tasks had died with an exception that submit swallowed into its Future. I wrapped the loop in a try/catch and nothing was thrown, so these are plain lost updates.

ConcurrentHashMap makes merge and computeIfAbsent atomic per key, which makes it the usual pick for an in-memory cache or counter shared across requests. Collections.synchronizedMap also works, but it puts one lock around the whole map. Queues, executors and async composition belong to the concurrency cluster.

Common traps

Removing inside a for-each loop. This one surprised me while preparing the example. My first version removed "expired-2" from ["ok-1", "expired-2", "ok-3"] and did not throw at all.

List<String> tokens = new ArrayList<>(List.of("ok-1", "expired-2", "expired-3"));
for (String t : tokens) {
    if (t.startsWith("expired")) tokens.remove(t);
}
System.out.println(tokens);
Enter fullscreen mode Exit fullscreen mode
[ok-1, expired-3]
Enter fullscreen mode Exit fullscreen mode

Removing the second-to-last element makes the iterator think it has finished, so the loop ends and expired-3 is never checked. With the expired token first, you get the exception everyone knows:

Exception in thread "main" java.util.ConcurrentModificationException
    at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1095)
    at java.base/java.util.ArrayList$Itr.next(ArrayList.java:1049)
Enter fullscreen mode Exit fullscreen mode

The fix is tokens.removeIf(t -> t.startsWith("expired"));, which prints [ok-1] for the list above. The silent version is the worse bug, because nothing crashes; only a test that checks the resulting list catches it.

List.of rejects null. An optional field from a request is enough to trigger it.

String middleName = null;
List<String> parts = List.of("Vu", middleName, "Duong");
Enter fullscreen mode Exit fullscreen mode
Exception in thread "main" java.lang.NullPointerException
    at java.base/java.util.Objects.requireNonNull(Objects.java:233)
Enter fullscreen mode Exit fullscreen mode

Even List.of("USER", "ADMIN").contains(null) throws the same NullPointerException, while an ArrayList would return false. Filter nulls first, or use new ArrayList<>() if null is a legal value.

A mutable field in hashCode. The Cart class below defines equals and hashCode from couponCode, and the code changes that field after adding the cart to a HashSet.

Set<Cart> carts = new HashSet<>();
Cart cart = new Cart("SALE10");
carts.add(cart);

cart.couponCode = "SALE20";               // field used by hashCode changes
System.out.println(carts.contains(cart)); // same object!
System.out.println(carts.size());
Enter fullscreen mode Exit fullscreen mode
false
1
Enter fullscreen mode Exit fullscreen mode

Warning: the set still holds the cart, but it looks in the bucket for the new hash and finds nothing. The same happens with HashMap keys. Keep fields used by hashCode immutable (a record does this for you, as long as its fields are immutable types too), or remove the object, change it, and add it again.

Arrays.asList is fixed-size. It wraps the array, so set works and add does not.

String[] fromCsv = {"a@x.dev", "b@x.dev"};
List<String> emails = Arrays.asList(fromCsv);
emails.add("c@x.dev");
Enter fullscreen mode Exit fullscreen mode
Exception in thread "main" java.lang.UnsupportedOperationException
    at java.base/java.util.AbstractList.add(AbstractList.java:155)
Enter fullscreen mode Exit fullscreen mode

Wrap it in new ArrayList<>(Arrays.asList(fromCsv)) when the list must grow.

Next step

Most of these collections end up feeding streams, through toMap, groupingBy or an Optional from findFirst. The next post in the series covers the patterns worth keeping there and the traps. Other posts on lists, sets and maps are collected under Java collections. For the official overview of every interface and implementation, see the Java Collections Framework guide.

Top comments (0)