2

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?

Alexander Ivanchenko
  • 25,667
  • 5
  • 22
  • 46
station
  • 6,715
  • 14
  • 55
  • 89

2 Answers2

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());
Ashish Patil
  • 4,428
  • 1
  • 15
  • 36
  • 3
    There’s no reason to use a `map` step, to be immediately followed by `flatMap`. A single step is enough: `.flatMap(step -> step.getJump().getValue().stream())`. On the other hand, repeated calls to `getJump` could be avoided: `myList.getJumps().stream() .map(Step::getJump) .filter(Objects::nonNull) .flatMap(step -> step.getValue().stream()) .collect(Collectors.toList());` – Holger May 16 '22 at 14:43
1

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());
Alexander Ivanchenko
  • 25,667
  • 5
  • 22
  • 46