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.
The book Effective Java mentions the following:
Container types, including collections, maps, streams, arrays, and optionals should not be wrapped in optionals. (P.252)
I don't really see the benefit of using Optional
, it would be more readable without it :
List<Bar> bars = listOfFoos.stream()
.map(Foo::getId)
.map(service::getBars)
.collect(Collectors.toList());
if (bars.isEmpty()) {
throw new ResourceNotFoundException(Bar.class, OBJECT_NULL);
}
Just add an Optional.filter
for it then. You could do it as :
List<Bar> 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
.