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.
I would like to ensure that this method will throw ResourceNotFoundException in case there is no items on bars list, although in the current state it checks if list bars is null and it is not, since it contains an empty list.
Could you please help me and suggest some solution?
List<Bar> bars = Optional.ofNullable(
listOfFoos.stream()
.map(Foo::getId)
.map(fooId -> service.getBars(fooId))
.filter(Objects::nonNull)
.collect(Collectors.toList()))
.orElseThrow(() -> new ResourceNotFoundException(Bar.class, OBJECT_NULL));
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);
}
The book Effective Java mentions the following:
Container types, including collections, maps, streams, arrays, and optionals should not be wrapped in optionals. (P.252)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With