Java Optional orElseThrow with empty collection

后端 未结 3 1587
情深已故
情深已故 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:27

    I don't really see the benefit of using Optional, it would be more readable without it :

    List bars = listOfFoos.stream()
       .map(Foo::getId)       
       .map(service::getBars)                    
       .collect(Collectors.toList());
    
    if (bars.isEmpty()) {
       throw new ResourceNotFoundException(Bar.class, OBJECT_NULL);
    }
    

提交回复
热议问题