java – Returns the empty element from the Java 8 map operation

Replace the call map with flatMap. The operation map produces an output value per input value, while the operation flatMap produces any number of output values ​​per input value – include zero.

The easiest way is probably to replace the check like this:

List output = input.stream()
                            .flatMap(i -> { 
                                Integer out = crazyFunction(i);
                                if (out == null || out.equals(0))
                                    return Stream.empty();
                                else
                                    return Stream.of(out);
                                })
                            .collect(Collectors.toList());

Further refactoring may change crazyFunction to get it to return a Optional (probably OptionalInt). If you call him from mapthe result is a Stream. So it is necessary flatMap that flow to remove the empty optionals:

List output = input.stream()
    .map(this::crazyFunctionReturningOptionalInt)
    .flatMap(o -> o.isPresent() ? Stream.of(o.getAsInt()) : Stream.empty())
    .collect(toList());

The result of flatMap it’s a Stream which encloses i intyes, but that’s fine since you’ll be sending them in a List. If you weren’t going to enclose the values int in Listyou could convert Stream to a IntStream using the following:

flatMapToInt(o -> o.isPresent() ? IntStream.of(o.getAsInt()) : IntStream.empty())

For further discussion on managing option flows, see this question and its answers .

Leave a comment