连接可选列表 [英] Concatenate Optional Lists

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

问题描述

我有三个Optional>,它们必须组合起来并返回.我尝试使用Optional.map()flatmap(),但未成功.

I have three Optional> which have to be combined and returned. I tried to use Optional.map() and flatmap() but was not successful.

public Optional<List<Entiy>> getRecords() {
    Optional<List<Entiy>> entity1 = repo.findAllByStatus("1");
    Optional<List<Entiy>> entity2 = repo.findAllByStatus("2");
    Optional<List<Entiy>> entity3 = repo.findAllByStatus("3");
    //Need to return a concatenation of entity1, 2 and 3
}

任何有关如何有效执行操作的想法?

Any thoughts on how to do is efficiently?

推荐答案

类似的东西:

return Optional.of(Stream.of(entity1.orElse(new ArrayList<>()), entity2.orElse(new ArrayList<>()), entity3.orElse(new ArrayList<>()))
            .flatMap(List::stream)
            .collect(Collectors.toList()));

或更容易理解为:

return Optional.of(Stream.of(entity1, entity2, entity3)
        .filter(Optional::isPresent)
        .map(Optional::get)
        .flatMap(List::stream)
        .collect(Collectors.toList()));

这篇关于连接可选列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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