Java collections: choosing between List, Set, Map and Deque
ArrayList vs LinkedList, HashMap vs TreeMap, HashSet vs LinkedHashSet, ArrayDeque for stacks and queues: what each costs and which to reach for first.
The Java Collections Framework gives you a handful of interfaces (List, Set, Map, Deque)
and several implementations of each. Pick the interface for what you need to do, and the
implementation for how it should behave.
Program to the interface
List<String> titles = new ArrayList<>(); // not ArrayList<String> titles
Map<String, Integer> stock = new HashMap<>();Declaring variables and parameters as the interface means you can swap the implementation later without touching the code that uses it.
The default choices
| You need | Use | Cost |
|---|---|---|
| An ordered, indexable sequence | ArrayList | get O(1), add O(1) amortised |
| Unique items, fast "contains?" | HashSet | O(1) average |
| Key → value lookups | HashMap | O(1) average |
| Keys in sorted order, ranges | TreeMap / TreeSet | O(log n) |
| Insertion order preserved | LinkedHashMap / LinkedHashSet | O(1) average |
| A stack or a queue | ArrayDeque | O(1) at both ends |
| Always take the smallest next | PriorityQueue | O(log n) add/poll |
LinkedList, Stack and Vector are rarely the right answer: ArrayDeque replaces the first two
for stacks and queues, and Vector is a legacy synchronised ArrayList.
Working with maps
Map<String, Integer> loans = new HashMap<>();
loans.merge("Dune", 1, Integer::sum); // count up, starting at 1
int count = loans.getOrDefault("Heat", 0); // 0 when absent
loans.computeIfAbsent("Emma", k -> new ArrayList<>()); // group values in lists
for (Map.Entry<String, Integer> e : loans.entrySet()) {
System.out.println(e.getKey() + ": " + e.getValue());
}A HashMap's iteration order is unspecified and can change between runs or Java versions. If your
output must be stable, use LinkedHashMap (insertion order) or TreeMap (sorted).
Sorted maps answer range questions
TreeMap<Integer, String> slots = new TreeMap<>();
slots.put(900, "Ana"); slots.put(1030, "Ben"); slots.put(1400, "Cy");
slots.floorKey(1100); // 1030: the latest slot at or before 11:00
slots.ceilingKey(1100); // 1400: the next slot after 11:00
slots.subMap(900, 1200); // slots from 09:00 up to (not including) 12:00Immutable collections
Java 9+ has compact factory methods:
List<String> days = List.of("Mon", "Tue", "Wed");
Map<String, Integer> prices = Map.of("child", 6, "adult", 11);They throw UnsupportedOperationException on add or put, and they reject null. Return them
(or List.copyOf(...)) from methods so callers can't change your internal state.
Iterating safely
Removing from a list inside a for-each loop throws ConcurrentModificationException. Use
removeIf:
loans.entrySet().removeIf(e -> e.getValue() == 0);Common mistakes
- Comparing
Integerobjects with==(it compares references above 127): useequals. - Using a mutable object as a
HashMapkey and then changing it. - Custom key classes without
equalsandhashCode(see the next guide).
Collections run through Java Fundamentals and Java Intermediate.
Questions and answers
- Should I use ArrayList or LinkedList in Java?
- ArrayList, almost always. It has O(1) access by index and is far more cache-friendly. LinkedList only wins when you insert or remove at both ends constantly, and ArrayDeque does that better too.
- What is the difference between HashMap and TreeMap?
- HashMap gives O(1) average get and put with no ordering. TreeMap keeps keys sorted, costs O(log n) per operation, and adds navigation methods like floorKey, ceilingKey and subMap for range queries.
Practise it
Read next
- Java equals and hashCode: the contract and why HashMap depends on it
What == really compares, how to write equals and hashCode correctly, why breaking the contract makes HashSet lose objects, and the shortcuts that do it for you.
- Java streams and lambdas: filter, map, collect and groupingBy
Lambdas and method references, the stream pipeline, collecting into lists and maps, groupingBy for reports, Optional, and when a plain loop is clearer.