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 map
the 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 int
yes, but that’s fine since you’ll be sending them in a List
. If you weren’t going to enclose the values int
in List
you 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 .