archive2015

Java 8 streams: the patterns I use and six pitfalls

Everyday Java 8 stream patterns, and the mistakes that cause exceptions or slow code: toMap duplicates, parallel streams, Optional.get and more.

3 min read#dev#java

Java 8 came out in March 2014, and by now streams and lambdas are in normal business code. In code reviews I keep writing the same comments, so I am collecting them here, together with the patterns I use.

Patterns that make code clearer

Filter and map a list:

List<String> activeNames = users.stream()
        .filter(User::isActive)
        .map(User::getName)
        .collect(Collectors.toList());

Group by a key:

Map<String, List<Order>> byCountry = orders.stream()
        .collect(Collectors.groupingBy(Order::getCountry));

Count per key:

Map<String, Long> countByStatus = orders.stream()
        .collect(Collectors.groupingBy(Order::getStatus, Collectors.counting()));

Sum a field:

BigDecimal total = orders.stream()
        .map(Order::getAmount)
        .reduce(BigDecimal.ZERO, BigDecimal::add);

Join strings:

String csv = names.stream().collect(Collectors.joining(","));

These are shorter than the loop and easy to read.

1. Collectors.toMap with duplicate keys

Map<String, User> byEmail = users.stream()
        .collect(Collectors.toMap(User::getEmail, u -> u));

If two users have the same email, this throws IllegalStateException: Duplicate key. It passes the tests and then fails with real data. Decide what happens with duplicates and pass a merge function:

Map<String, User> byEmail = users.stream()
        .collect(Collectors.toMap(User::getEmail, u -> u, (first, second) -> first));

toMap also throws NullPointerException if a value is null.

2. parallelStream() as a speed button

parallelStream() uses the common ForkJoinPool, which all parallel streams in the JVM share. Its size is the number of CPU cores minus one. If the work blocks on a database or HTTP call, you block the shared pool and other parallel streams in the application wait. For small lists the cost of splitting the work is larger than the gain. And shared mutable state in the lambda gives wrong results with no error.

I use sequential streams by default. parallelStream() only for CPU-heavy work on large data, with no I/O, and only after measuring.

3. Optional.get() without a check

User u = users.stream().filter(x -> x.getId() == id).findFirst().get();

If nothing matches, this throws NoSuchElementException. It is the old unchecked null bug with a new name. Use orElse, ifPresent, or orElseThrow with a clear message:

User u = users.stream()
        .filter(x -> x.getId() == id)
        .findFirst()
        .orElseThrow(() -> new IllegalArgumentException("No user " + id));

4. Reusing a stream

A stream can be used once. A second terminal operation throws IllegalStateException: stream has already been operated upon or closed. Store the collection, not the stream, and call .stream() again.

5. Checked exceptions in lambdas

Function and Predicate do not declare checked exceptions, so this does not compile:

files.stream().map(f -> Files.readAllLines(f)).collect(Collectors.toList()); // IOException

Often a normal loop is the clearest fix. The other way is a small helper that throws UncheckedIOException (new in Java 8):

private static List<String> readLines(Path p) {
    try {
        return Files.readAllLines(p);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

List<List<String>> all = files.stream().map(MyClass::readLines).collect(Collectors.toList());

6. Side effects in map and peek

map should only transform. peek is for debugging. If you need to change something, do it in forEach at the end, or create new objects. Streams are also lazy: nothing runs until a terminal operation like collect. A map with side effects on a stream that is never collected does nothing at all, which can be confusing to debug.

When I write a loop instead

When the logic has several if branches and early returns, when I need the index, when each item needs its own checked exception handling, or when I write to several collections at once. Also when a stream chain needs a comment to explain it. In that case I try the loop and keep whichever is easier to read.