在Java 8中懒惰地返回第一个非空列表 [英] Return first non empty list lazyily in Java 8

查看:679
本文介绍了在Java 8中懒惰地返回第一个非空列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有N个列表从存储库返回数据。我想返回这三个列表中的第一个非空(每个列表执行不同的SQL来获取数据)。

I have N lists that return data from a Repository. I want to return the first non empty of these three lists (each one executes a different SQL to fetch data).

问题是我想懒得这样做,所以如果我已经找到了可接受的结果,我就不需要在数据库上执行SQL。我的代码是(已修改)

The catch is that I want to do this lazily, so that I don't need to execute a SQL on the database if I have already found an acceptable result. My code is (modified)

@Override
public List<Something> dataService(Data data) {

return firstNonEmptyList(repository.getDataWayOne(data.getParameter()), 
                         repository.getDataWayTwo(data.getParameter()),
                         repository.getDataWayThree(data.getParameter().getAcessoryParameter())
                         Collections.singletonList(repository.getDefaultData(data.getParameter()));

}

@SafeVarargs
private final List<Something> firstNonEmptyList(List<Something>... lists) {
for (List<Something> list : lists) {
  if (!list.isEmpty()) {
    return list;
  }
}

return null;

}

这有效,但不是很懒。有什么想法吗?

This works, but it isn't lazy. Any ideas?

推荐答案

您可以制作供应商流并按照订单顺序对其进行评估,直至找到结果:

You can make a stream of suppliers and evaluate them in encounter order until you find a result:

return Stream.<Supplier<List<Something>>>of(
            () -> repository.getDataWayOne(data.getParameter()),
            () -> repository.getDataWayTwo(data.getParameter()),
            () -> repository.getDataWayThree(data.getParameter().getAcessoryParameter()),
            () -> Collections.singletonList(repository.getDefaultData(data.getParameter()))
        )
        .map(Supplier::get)
        .filter(l -> !l.isEmpty())
        .findFirst()
        .orElse(null);

每个供应商定义如何访问结果集,而不实际尝试直到执行map()。由于 filter() map() 无状态 操作,将调用每个供应商及其结果在尝试下一个之前验证。如果找到非空结果,则流将立即终止,因为 findFirst() 短路

Each supplier defines how to access a result set, without actually attempting it until map() is executed. Since filter() and map() are stateless operations, each supplier will be called and its result validated before the next one is attempted. If a non-empty result is found, the stream will terminate immediately, because findFirst() is short-circuiting.

这篇关于在Java 8中懒惰地返回第一个非空列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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