我有N個從存儲庫返回數據的列表。我想返回這三個列表中的第一個非空(每個執行一個不同的SQL來獲取數據)。在Java 8中懶惰地返回第一個非空列表
問題是我想懶惰地這樣做,這樣如果我已經找到可接受的結果,就不需要在數據庫上執行SQL。我的代碼是(修改)
@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;
}
這是有效的,但它不是懶惰。有任何想法嗎?
糾正我,如果我錯了,但我認爲這將是懶惰的,如果你包裝列表調用lambdas裏面。在'firstNonEmptyList'中,您將評估每個lambda,直到找到您想要的(即返回非空列表的那個)。非調用lambdas永遠不會執行查詢。無論如何,shmosel提供的解決方案可以完成我所描述的任務,並且更加優雅。 – Gabriel