Java and Spring Level 2 This level · 66 of 84
Medium java spring

Stream.concat of two lists then sorted, and one list contains null?

The 30 second answer

Concat itself is fine with null elements in either list, but sorted uses natural ordering, so comparing a null throws NullPointerException at the terminal operation because streams are lazy. Filter nulls out first, or sort with Comparator nullsFirst or nullsLast so nulls have a defined place in the result.

Could you say this in an interview?

concat is fine with nulls; sorted() uses natural ordering, so comparing null throws **NullPointerException** (at the terminal operation, since streams are lazy). Fix: filter(Objects::nonNull) or sorted(Comparator.nullsFirst(Comparator.naturalOrder())) / nullsLast.

.filter(Objects::nonNull)
.sorted()

// or keep nulls in a defined position:
.sorted(Comparator.nullsFirst(Comparator.naturalOrder()))
Sources (2)
  1. Stream.sorted / concatdocs.oracle.com
  2. Comparator.nullsFirstdocs.oracle.com
Previous
Next