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.

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:

Sources (0)
See inline citations in the answer above.