Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Optional orElseThrow with empty collection

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));
like image 761
gariaable Avatar asked Dec 01 '22 09:12

gariaable


2 Answers

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);
}
like image 62
Olivier Boissé Avatar answered Dec 03 '22 23:12

Olivier Boissé


The book Effective Java mentions the following:

Container types, including collections, maps, streams, arrays, and optionals should not be wrapped in optionals. (P.252)

like image 34
logbasex Avatar answered Dec 04 '22 01:12

logbasex