Java Optional orElseThrow with empty collection

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

    Just add an Optional.filter for it then. You could do it as :

    List 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.

提交回复
热议问题