具有空集合的Java可选orElseThrow [英] Java Optional orElseThrow with empty collection

查看:761
本文介绍了具有空集合的Java可选orElseThrow的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个流,在其中使用集合 listOfFoo 来获取该列表中所有项目的ID,并使用它们来获取Bar实例的值.

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.

我要确保此方法在栏列表上没有任何项目的情况下会抛出 ResourceNotFoundException ,尽管在​​当前状态下它会检查列表栏是否为null,否则检查列表栏是否为null包含一个空列表.

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));

推荐答案

然后只需为其添加一个Optional.filter.您可以按照以下方式进行操作:

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));

此外:通过代码中共享的实现,流返回的列表不能为null,因此Optional.ofNullable可能被Optional.of代替.

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.

这篇关于具有空集合的Java可选orElseThrow的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆