Search code examples
javanullpointerexceptionnulljava-streamoption-type

How to delete Null-elements from the Stream before applying collect?


My stream function sometime returns 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 inside the map() method, it will rise NullPointException.

How to make this stream not rise an exception and when all elements are null make it to return an empty list or null?


Solution

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