Video in progress

Strong Middle 🌊 Streams and lambdas

If a stream has null elements, which operations fail, and how do you clean out the nulls properly?

A stream itself allows null elements, but findFirst, max, min, sorted() with natural ordering, a toMap value, a groupingBy key and toUnmodifiableList throw an NPE on null. To clean up, use filter(Objects::nonNull), and for a single nullable value, Java 9's Stream.ofNullable.

📖 Answer

The problem usually comes from external data: an empty field in JSON, a nullable column in JPA, a list element returned as null from an old API.

List<String> emails = Arrays.asList("a@x.uz", null, "b@x.uz");

emails.stream().map(String::toLowerCase).toList();   // NPE, inside map
emails.stream().sorted().toList();                   // NPE, compareTo
emails.stream().findFirst();                         // NPE if the first one is null
emails.stream().collect(Collectors.toSet());         // works, null goes in the set
emails.stream().toList();                            // works

Cleaning:

List<String> clean = emails.stream()
        .filter(Objects::nonNull)
        .map(String::toLowerCase)
        .toList();

A stream from a single nullable value (for example inside flatMap):

orders.stream()
      .flatMap(o -> Stream.ofNullable(o.coupon()))   // if null, an empty stream
      .toList();

If the collection itself can be null: Stream.ofNullable(list).flatMap(List::stream) or, better, require the source to return an empty list instead of null.

I usually clean nulls at the boundary, when going from a DTO to a domain object. If != null checks spread to every step inside the pipeline, that's a sign of a problem in the data model.