Home > OS >  How to delete null in stream for stream collect?
How to delete null in stream for stream collect?

Time:07-01

My stream function sometime return null, when I do collect them How to delete that null return?

versions.stream().map(vs->{
        if(vs.matches("^matched string$")) {
                ...
                return new VersionNumber(tmp[0], tmp[1], tmp[2]));
        }
        return null;
    }).flatMap(Optional::stream).collect(Collectors.toList());

For this stream functions, if all matched is false, I mean if all the function in .map method, it will rise NullPointException. How to make this stream not rise that exception and when all null it will return empty or null?

CodePudding user response:

You can filter afterward

versions.stream().map(vs->{
        if(vs.matches("^matched string$")) {
                ...
                return new VersionNumber(tmp[0], tmp[1], tmp[2]));
        }
        return null;
    }).filter(Objects::nonNull).flatMap(Optional::stream).collect(Collectors.toList());

But that is wiser to filter the sooner

versions.stream().filter(vs -> vs.matches("^matched string$"))
                 .map(vs->{
                           ...
                           return new VersionNumber(tmp[0], tmp[1], tmp[2]));
    }).flatMap(Optional::stream).collect(Collectors.toList());

CodePudding user response:

if all matched is false, I mean if all the function in .map method, it will rise a NullPointException

Since you're getting a NullPointerException that means that your code compiles and running. Therefore, I assume that the "code" inside the map() operation doesn't your actual code because we can't treat elements in the of Stream<VersionNumber> as optionals.

flatMap(Optional::stream) will not cause a compilation error only if preceding map() produces a result of type Optional<VersionNumber>.

Hence, my suggestion is simple: never return null in place of optional. It's completely wrong when an optional object might be null, it should either contain a value or be empty, but it should never be null.

And as @Andy Thomas has pointed out in the comment, there's no reason to utilize Optional if the code inside the map() really creates the object on the spot like new VersionNumber(tmp[0], tmp[1], tmp[2]));. In this case, wrapping the result of the map() with an Optional will be a misuse of optional. Return either VersionNumber instance or null. And then apply a filter:

.filter(Objects::nonNull)

You have to resort to the usage of optional only if inside the map you're actually not creating VersionNumber as you've shown, but, for instance, making an API call which return an Optional<VersionNumber> if some condition is meat.

.map(vs -> {
    if (vs.matches("^matched string$")) {
        ...
        return getVersionNumber(tmp[0], tmp[1], tmp[2]) // method returing Optional<VersionNumber>
    }
    return Optional.empty();
}

In such a case, there's no need to apply filtering. Optional.stream() when invoked on an empty optional produces an empty stream.

CodePudding user response:

As of java 16, there is also Stream.mapMulti:

Returns a stream consisting of the results of replacing each element of this stream with multiple elements, specifically zero or more elements.

Using this, your example becomes

versions.stream().mapMulti((vs, consumer)->{
        if(vs.matches("^matched string$")) {
                ...
                consumer.accept(new VersionNumber(tmp[0], tmp[1], tmp[2]));
        }    }).collect(Collectors.toList());
  • Related