'How to apply a null-check within Stream#map() [duplicate]

I have the following piece of code:

 myList.getJumps().stream()
            .map(step -> step.getJump().getValue())
            .flatMap(List::stream)
            .collect(Collectors.toList());

There is a chance that step.getJump() can be null.

Is there an efficient way to avoid a NPE there?



Solution 1:[1]

As @HariHaravelan mentioned in comments:

myList.getJumps().stream()
            .filter(step-> step.getJump()! = null)
            .map(step -> step.getJump().getValue())
            .flatMap(List::stream)
            .collect(Collectors.toList());

Or even:

myList.getJumps().stream()
                .filter(step-> Objects.nonNull(step.getJump())
                .map(step -> step.getJump().getValue())
                .flatMap(List::stream)
                .collect(Collectors.toList());

Solution 2:[2]

There's nothing wrong with explicate null-check. If we apply it inside the flatMap() operation a non-null list step.getJump() should spawn a stream, otherwise an empty stream needs to be provided:

myList.getJumps().stream()
    .flatMap(step -> step.getJump() != null ?
        jump.getValue().stream() : Stream.empty())
    .collect(Collectors.toList());

Starting with Java 9 we can utilize Stream.ofNullable() that creates either a singleton stream or an empty stream:

myList.getJumps().stream()
    .flatMap(step -> Stream.ofNullable(step.getJump())
        .flatMap(jump -> jump.getValue().stream())
    .collect(Collectors.toList());

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ashish Patil
Solution 2 Alexander Ivanchenko