Home > Enterprise >  How to apply a null-check within Stream#map()
How to apply a null-check within Stream#map()

Time:05-17

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?

CodePudding user response:

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());

CodePudding user response:

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());
  • Related