Java Optional orElseThrow with empty collection

后端 未结 3 1546
情深已故
情深已故 2021-01-14 05:03

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.

相关标签:
3条回答
  • 2021-01-14 05:11

    The book Effective Java mentions the following:

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

    0 讨论(0)
  • 2021-01-14 05:27

    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);
    }
    
    0 讨论(0)
  • 2021-01-14 05:32

    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.

    0 讨论(0)
提交回复
热议问题