Almost every program is about groups of things
An online shop has a basket of items, a catalogue of products, a set of customers who opted out of email, and a queue of orders to pack. A school timetable has rooms, teachers, classes and the map between them. Very little real code deals with one value at a time.
Java's standard library gives you a carefully designed Collections Framework: a small set of interfaces (List, Set, Map, Deque...) and well-tuned implementations of each. Using it well is mostly about two decisions. First, which interface describes what you need: an ordered sequence, a group without duplicates, a lookup table, a queue? Second, which implementation gives that behaviour at the right cost? Get those right and the code is short, fast and obviously correct. Get them wrong and you get the classic performance bug: a contains on a list of a million items, inside a loop over another million.
The second half of the lesson is about streams, Java's way of describing a computation over a collection as a pipeline ("keep the runners under 135 minutes, take their names, sort them") rather than as a loop. Streams arrived in Java 8 and changed how Java is written; every professional codebase uses them.
The framework at a glance
Definition— The core interfaces
List: an ordered sequence with positions, duplicates allowed. Set: no duplicates, as decided by equals. Map: keys mapped to values, each key at most once (a Map is not a Collection, but belongs to the framework). Deque ("deck"): a double-ended queue, usable as a FIFO queue or a LIFO stack. Since JDK 21, the ordered ones share SequencedCollection and SequencedMap, with getFirst, getLast, addFirst, addLast and reversed.
Write declarations against the interface and choose the implementation once, at construction: List<String> names = new ArrayList<>();. Then you can change the implementation without touching the rest of the code. The implementations you will actually use:
| You need | Use | Cost of the key operations | Notes |
|---|---|---|---|
| A growable sequence | ArrayList | get by index ; add at end amortised ; insert or remove in the middle ; contains | The default list. |
| A queue or stack | ArrayDeque | add and remove at either end | Prefer it to Stack and LinkedList. |
| Fast membership tests | HashSet | add, remove, contains on average | No order. |
| A set in insertion order | LinkedHashSet | as HashSet | Iterates in the order elements were added. |
| A sorted set | TreeSet | add, remove, contains | Also first, floor, ceiling, ranges. |
| A lookup table | HashMap | get, put on average | No order. The default map. |
| A map in insertion order | LinkedHashMap | as HashMap | Can also act as an LRU cache. |
| A sorted map | TreeMap | get, put | Keys in order; range queries. |
| Highest-priority first | PriorityQueue | add, remove-min ; peek | A binary heap. |
HashSet and HashMap are hash tables and depend on the elements' hashCode and equals methods being consistent, a contract we study in Exceptions, equality and immutability. TreeSet and TreeMap are red–black trees and need elements that are Comparable, or a Comparator. LinkedList exists but is rarely the right choice: it uses far more memory than ArrayList and is slow to traverse, and its theoretical advantage (cheap insertion in the middle) needs you to be at that position already.
Definition— Unmodifiable collections
List.of(...), Set.of(...), Map.of(...) (Java 9) and List.copyOf(...) (Java 10) create collections that throw UnsupportedOperationException on any attempt to change them. They reject null elements. Set.of and Map.of deliberately have no fixed iteration order, so never depend on it. Collections.unmodifiableList(list) is different: it is a read-only view of a list that someone else may still change.
Lists, sets and maps at work
import java.util.*;
public class Main {
public static void main(String[] args) {
// List: ordered, indexed, duplicates allowed
List<String> queue = new ArrayList<>(List.of("Amara", "Bao", "Chidi"));
queue.add("Dilnoza");
queue.addFirst("Esi"); // sequenced-collection method, JDK 21
System.out.println(queue + " first=" + queue.getFirst() + " last=" + queue.getLast());
System.out.println("reversed: " + queue.reversed());
// Set: no duplicates; TreeSet keeps its elements sorted
Set<String> visited = new TreeSet<>(List.of("Quito", "Accra", "Hanoi", "Accra"));
System.out.println(visited + " contains Hanoi? " + visited.contains("Hanoi"));
// Map: keys to values. merge() is the idiomatic way to count
String text = "she sells sea shells by the sea shore";
Map<String, Integer> counts = new TreeMap<>();
for (String word : text.split(" ")) {
counts.merge(word, 1, Integer::sum);
}
System.out.println(counts);
System.out.println("dog: " + counts.getOrDefault("dog", 0));
// computeIfAbsent: group words by their first letter
Map<Character, List<String>> byLetter = new TreeMap<>();
for (String word : counts.keySet()) {
byLetter.computeIfAbsent(word.charAt(0), k -> new ArrayList<>()).add(word);
}
System.out.println(byLetter);
// Removing while iterating: use removeIf, not a for-each loop
List<Integer> numbers = new ArrayList<>(List.of(5, 12, 7, 20, 3));
try {
for (Integer n : numbers) {
if (n > 10) numbers.remove(n);
}
} catch (ConcurrentModificationException e) {
System.out.println("ConcurrentModificationException");
}
numbers.removeIf(n -> n > 10);
System.out.println(numbers);
// Unmodifiable collections refuse changes
List<String> fixed = List.of("a", "b");
try {
fixed.add("c");
} catch (UnsupportedOperationException e) {
System.out.println("List.of is unmodifiable");
}
}
}[Esi, Amara, Bao, Chidi, Dilnoza] first=Esi last=Dilnoza
reversed: [Dilnoza, Chidi, Bao, Amara, Esi]
[Accra, Hanoi, Quito] contains Hanoi? true
{by=1, sea=2, sells=1, she=1, shells=1, shore=1, the=1}
dog: 0
{b=[by], s=[sea, sells, she, shells, shore], t=[the]}
ConcurrentModificationException
[5, 7, 3]
List.of is unmodifiableThe patterns here are ones you will type every week:
List.of(...)insidenew ArrayList<>(...)is the standard way to get a modifiable list with some starting elements.counts.merge(word, 1, Integer::sum)means: ifwordis absent, store 1; otherwise combine the old value and 1 withInteger::sum. It replaces four lines of get-check-put.Integer::sumis a method reference, a compact lambda for(a, b) -> Integer.sum(a, b).getOrDefaultavoids anullcheck for missing keys.computeIfAbsent(key, k -> new ArrayList<>())returns the list for a key, creating and storing it first if needed. It is the idiom for building a map of lists ("multimap").- Never change a collection while a for-each loop iterates over it. Most collections detect it and throw
ConcurrentModificationException(here, after the loop had already removed 12, which is why the exception is a symptom rather than a safety net: detection is best-effort and not guaranteed). UseremoveIf, an explicitIteratorwith its ownremove(), or build a new collection. - The
TreeSetandTreeMapprint in sorted order. AHashMapwould print in an order that depends on hash codes and table size, which can change between JDK versions. If order matters, choose a structure that guarantees one.
Sorting and stream pipelines
The next program works on the results of a club's 30 km race. It uses a record, a compact way to declare an immutable data class with a constructor, accessors (name(), minutes()), equals, hashCode and toString; the next lesson is about records in depth.
import java.util.*;
import java.util.stream.*;
public class Main {
// A record is a compact, immutable data class (more in the next lesson)
record Runner(String name, String country, int minutes) {}
public static void main(String[] args) {
List<Runner> results = List.of(
new Runner("Njeri", "KE", 131),
new Runner("Dawit", "ET", 128),
new Runner("Ingrid", "NO", 140),
new Runner("Achieng", "KE", 128),
new Runner("Lucía", "MX", 137),
new Runner("Selam", "ET", 135));
// Sort by time, then by name; the original list is unmodifiable, so copy it first
List<Runner> podium = new ArrayList<>(results);
podium.sort(Comparator.comparingInt(Runner::minutes).thenComparing(Runner::name));
for (int i = 0; i < 3; i++) {
System.out.println((i + 1) + ". " + podium.get(i).name() + " " + podium.get(i).minutes());
}
// The same idea as a stream pipeline: filter, map, collect
List<String> under135 = results.stream()
.filter(r -> r.minutes() < 135)
.map(Runner::name)
.sorted()
.toList();
System.out.println(under135);
// Aggregates
IntSummaryStatistics stats = results.stream().mapToInt(Runner::minutes).summaryStatistics();
System.out.println("min=" + stats.getMin() + " max=" + stats.getMax() + " avg=" + stats.getAverage());
// Grouping: runners per country, and the best time per country
Map<String, Long> perCountry = results.stream()
.collect(Collectors.groupingBy(Runner::country, TreeMap::new, Collectors.counting()));
System.out.println(perCountry);
Map<String, String> bestPerCountry = results.stream()
.collect(Collectors.groupingBy(Runner::country, TreeMap::new,
Collectors.collectingAndThen(
Collectors.minBy(Comparator.comparingInt(Runner::minutes)),
best -> best.orElseThrow().name())));
System.out.println(bestPerCountry);
String names = results.stream().map(Runner::name).collect(Collectors.joining(", ", "[", "]"));
System.out.println(names);
}
}1. Achieng 128
2. Dawit 128
3. Njeri 131
[Achieng, Dawit, Njeri]
min=128 max=140 avg=133.16666666666666
{ET=2, KE=2, MX=1, NO=1}
{ET=Dawit, KE=Achieng, MX=Lucía, NO=Ingrid}
[Njeri, Dawit, Ingrid, Achieng, Lucía, Selam]Comparators compose. Comparator.comparingInt(Runner::minutes) builds a comparator from a "key extractor"; .thenComparing(Runner::name) breaks ties; .reversed() would flip the order. This style replaces hand-written compare methods, which are a rich source of bugs (subtracting two ints to compare them, for instance, overflows for large values).
A stream pipeline has three parts: a source (results.stream()), zero or more intermediate operations that each return a new stream (filter, map, sorted), and one terminal operation that produces a result (toList(), collect(...), count(), forEach(...)). Read it as a sentence: from the results, keep those under 135 minutes, take each name, sort, make a list. Stream.toList() (JDK 16) returns an unmodifiable list; collect(Collectors.toList()) is the older spelling you will see in existing code.
Collectors do the heavy lifting of turning a stream into a structure. groupingBy is SQL's GROUP BY: a classifier function, optionally a map factory (here TreeMap::new, for sorted output), and a "downstream" collector that summarises each group (counting(), minBy(...), toList(), averagingInt(...)...). joining builds strings with a separator, prefix and suffix.
Notice that mapToInt produced an IntStream. Primitive streams (IntStream, LongStream, DoubleStream) avoid boxing every number into an Integer and offer sum, average and summaryStatistics directly.
Laziness, Optional and gatherers
import java.util.*;
import java.util.stream.*;
void main() {
// Streams are lazy: nothing runs until a terminal operation, and only as much as needed
Optional<Integer> firstBigSquare = Stream.of(3, 8, 12, 15, 20)
.peek(n -> IO.println(" looking at " + n))
.map(n -> n * n)
.filter(sq -> sq > 100)
.findFirst();
IO.println("first square over 100: " + firstBigSquare.orElse(-1));
// Optional makes "maybe no answer" part of the type
Optional<String> longWord = Stream.of("sun", "moon", "star").filter(w -> w.length() > 5).findAny();
IO.println(longWord.isPresent() + " " + longWord.map(String::toUpperCase).orElse("none"));
// Primitive streams avoid boxing; reduce folds a stream into one value
int sumOfOddSquares = IntStream.rangeClosed(1, 9).filter(i -> i % 2 == 1).map(i -> i * i).sum();
IO.println("odd squares 1..9: " + sumOfOddSquares);
long product = LongStream.rangeClosed(1, 15).reduce(1, (a, b) -> a * b);
IO.println("15! = " + product);
// Gatherers (JDK 24) add custom intermediate operations, such as fixed-size windows
List<List<Integer>> weeks = IntStream.rangeClosed(1, 10).boxed()
.gather(Gatherers.windowFixed(4))
.toList();
IO.println(weeks);
// A stream can be consumed only once
Stream<String> once = Stream.of("a", "b");
IO.println(once.count());
try {
once.count();
} catch (IllegalStateException e) {
IO.println(e.getMessage());
}
} looking at 3
looking at 8
looking at 12
first square over 100: 144
false none
odd squares 1..9: 165
15! = 1307674368000
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]
2
stream has already been operated upon or closedStreams are lazy and element-by-element. The pipeline does not square all five numbers and then filter the list. Each element travels through the whole pipeline before the next one starts, and findFirst stops the source as soon as it has an answer, which is why 15 and 20 were never looked at. (peek exists for debugging exactly this; do not use it for real work.) Laziness is what makes Stream.iterate and other infinite sources usable, as long as something like limit or findFirst ends them.
Optional is a container holding one value or none. findFirst, findAny, max and min return one because a stream may be empty. Use orElse, orElseThrow, map and ifPresent rather than calling get() blindly. The JDK's own guidance is to use Optional as a return type for "there may be no result", not for fields or parameters.
reduce combines elements with an associative function and an identity, as in the factorial. 15! still fits in a long; 21! does not, and would overflow silently, as every long computation can.
Gatherers (final in JDK 24) let you write your own intermediate operations, and Gatherers ships some useful ones: windowFixed, windowSliding, fold, scan and mapConcurrent. Before them, grouping a stream into chunks of four needed awkward index arithmetic.
Loops or streams?
Both are professional Java. Streams shine for transformations and aggregations (filter, map, group, join), and their declarative style makes intent clear. Plain loops are better when the logic has early exits with side effects, several accumulators updated together, or checked exceptions (lambdas in standard functional interfaces cannot throw them). A three-line stream that replaces fifteen lines of loop is a win; a stream with nested lambdas spanning thirty lines is not. Performance is usually similar; measure before choosing for speed.
parallelStream() splits work across CPU cores. It helps only for large, CPU-bound workloads with no shared mutable state, and it can make small or I/O-bound pipelines slower. Treat it as an optimisation to measure, not a default.
Collections at the edges of your code
Most collection bugs in professional code are not inside loops; they are at the boundaries between classes, where one piece of code hands a collection to another. A few habits prevent nearly all of them.
Accept the most general type, return a specific promise. A method that only iterates should accept a Collection or even an Iterable; one that needs positions accepts a List. A method that returns a collection should say in its documentation whether the caller may modify it, and the simplest promise is "no": return List.copyOf(internal) or a toList() result.
Never return null for "nothing". Return an empty collection (List.of(), Map.of()). Every caller can then loop over the result without a null check, and an empty list is exactly what "no results" means.
Copy what you keep. If a constructor stores a list it was given, a caller who later changes that list changes your object behind your back. this.items = List.copyOf(items); both copies and freezes it, and it also rejects nulls early. This "defensive copy" is cheap insurance, and records in the next lesson use it constantly.
Collections compare by contents. Two lists are equals when they contain equal elements in the same order; two sets when they contain the same elements in any order; two maps when they have the same key–value pairs. That is why List.of(1, 2).equals(new ArrayList<>(List.of(1, 2))) is true even though the classes differ.
Mind the element type's contract. A HashSet of objects whose equals and hashCode disagree, or a TreeSet whose comparator is inconsistent with equals, silently loses or duplicates elements. And an object used as a key must not change in a way that affects its hash code while it is in the map, or the map will never find it again. Immutable keys (strings, numbers, records of immutable fields) avoid the problem entirely.
Common misconceptions
Misconception
"List.of returns an ArrayList." It returns an unmodifiable list of an unspecified class. Adding to it throws. Wrap it in new ArrayList<>(...) when you need to change it.
Misconception
"An unmodifiable list is immutable." It cannot be changed through that reference, but the elements themselves may be mutable objects, and a view from Collections.unmodifiableList reflects changes to the list behind it. True immutability needs unmodifiable collections of immutable elements.
Misconception
"HashMap keeps keys in insertion order." It keeps them in no promised order. Use LinkedHashMap for insertion order or TreeMap for sorted order.
Misconception
"A stream is like a list I can loop over twice." A stream is a one-shot pipeline. Keep the collection and call .stream() again when you need another pass.
Exercises
1. Collections and streams
Warm-upComputationalWhat does this compact source file print?
void main() {
IO.println(new TreeSet<>(List.of(5, 1, 4, 1)));
}
2. Collections and streams
CoreComputationalWhat does this program print?
void main() {
Map<Character, Integer> m = new HashMap<>();
for (char c : "banana".toCharArray()) {
m.merge(c, 1, Integer::sum);
}
IO.println(m.get('a') * 10 + m.size());
}
3. Collections and streams
CoreComputationalWhat does this program print?
void main() {
var lengths = Stream.of("kiwi", "fig", "banana", "plum")
.filter(s -> s.length() <= 4)
.map(String::length)
.toList();
IO.println(lengths);
}
4. Collections and streams
StretchComputationalHow many times does the lambda passed to map run? The program prints the count.
void main() {
int[] calls = {0};
var first = Stream.of(1, 2, 3, 4, 5, 6)
.map(n -> { calls[0]++; return n * 10; })
.filter(n -> n > 25)
.findFirst();
IO.println(calls[0]);
}
5. Collections and streams
Warm-upComputationalWhat does this print?
void main() {
IO.println(Stream.of("x", "y", "z").collect(Collectors.joining("-", "<", ">")));
}
6. Collections and streams
CoreHumanA web crawler must remember which of several million URLs it has already visited, and check each new link against that memory. Order does not matter. Which is the best choice?
7. Collections and streams
StretchHumanWhich statements about List.of(...), Set.of(...) and Map.of(...) are true? Choose all that apply.
Further reading and resources
- Java Collections Framework overview (Java SE 25) · OracleThe framework's own map of interfaces and implementations.
- java.util.stream package summary (Java SE 25 API) · OracleThe best single explanation of streams, laziness, statelessness and parallelism, from the JDK itself.
- JEP 431: Sequenced CollectionsgetFirst, getLast, addFirst and reversed on ordered collections (JDK 21).
- JEP 485: Stream GatherersCustom intermediate stream operations (JDK 24).
- Lumenary CS: Hash tablesHow HashMap and HashSet work inside.