Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional<T> does not handle null elements

As I experimented Optional<T> does not handle null elements, so in the following example it throws a NullPointerException in the last statement:

List<String> data = Arrays.asList("Foo", null, "Bar");
data.stream().findFirst().ifPresent(System.out::println);
data.stream().skip(1).findFirst().ifPresent(System.out::println);

So, I still have to explicitly deal with null and filter non-null elements, such as:

data.stream()
    .filter(item -> item != null)
    .skip(1)
    .findFirst()
    .ifPresent(System.out::println);

Is there any alternative that avoids dealing explicitly with null as: item != null

like image 704
Miguel Gamboa Avatar asked Dec 04 '25 17:12

Miguel Gamboa


1 Answers

You can use .filter(Objects::nonNull) using the method Objects.nonNull(…) added for this purpose.

There is no way to avoid explicit filtering, unless you avoid having nulls in your source list in the first place.

Note that it would be strange if the Optional handled the null in this case as it would yield an empty optional which had the semantic of “there is no first element” which implies “the stream was empty” which is just wrong.

Dealing with nulls explicitly is the cleanest solution here as it also allows you to explicitly tell whether you want .filter(Objects::nonNull).skip(1), .skip(1).filter(Objects::nonNull)

…or .map(s->s==null? "null-replacement": s).findFirst()

like image 74
Holger Avatar answered Dec 07 '25 07:12

Holger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!