I\'m implementing a stream in which I use a collection listOfFoo to get ids of all items in that list and use them to get values of Bar instances.
Just add an Optional.filter for it then. You could do it as :
List bars = Optional.ofNullable(
listOfFoos.stream().map(fooId -> service.getBars(fooId))
.filter(Objects::nonNull).collect(Collectors.toList()))
.filter(a -> !a.isEmpty())
.orElseThrow(() -> new ResourceNotFoundException(Bar.class, OBJECT_NULL));
Aside: By the implementation shared in the code, the list returned by the stream could not be null, so Optional.ofNullable could possibly be replaced by Optional.of.