Java-8 – optional, do not handle null elements

When I experiment with optional < T >, I do not process null elements, so in the following example, it throws 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);

Therefore, I still have to explicitly handle null and filter non null elements, for example:

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

Is there any alternative to explicitly handling null: item= null

Solution

It really depends on what you want to do If you want to treat null as a valid value, the answer is different from the answer to skip null values

If you want to keep "nulls" in the stream:

List<String> data = Arrays.asList("Foo","Bar");
    data.stream().map(Optional::ofNullable).findFirst().flatMap(Function.identity()).ifPresent(System.out::println);  ;
    data.stream().map(Optional::ofNullable).skip(1).findFirst().flatMap(Function.identity()).ifPresent(System.out::println);

If you want to remove null values from the stream, use data stream(). Filter (objects:: nonnull) filters it out (or as you said O – > o! = null, whatever you like

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>