JAVA Foreach到流
我正在尝试将foreach转换为streamsJAVA Foreach到流,java,foreach,java-8,java-stream,Java,Foreach,Java 8,Java Stream,我正在尝试将foreach转换为streams for (Entity entity : listOfEntitys.getAll()) { if (!isEntityDateValid(entity.getStartDate()) || !isEntityDateValid(entity.getEndDate())) { return false; } } 所以我把它转换成这样 if (lis
for (Entity entity : listOfEntitys.getAll()) {
if (!isEntityDateValid(entity.getStartDate())
|| !isEntityDateValid(entity.getEndDate())) {
return false;
}
}
所以我把它转换成这样
if (listOfEntitys.getAll() != null) {
return listOfEntitys.getAll().stream().anyMatch(entity-> !isEntityDateValid(entity.getStartDate())
|| !isEntityDateValid(entity.getEndDate()));
}
但是我把它搞砸了,因为它总是计算布尔值,我只想在它满足条件时返回它如果您只想在某些条件下返回,那么您的stream命令需要是
If
语句的一部分
if (listOfEntities.getAll()!=null && listOfEntities.getAll().stream().anyMatch(...)) {
return false;
}
但是使用可能会更清晰!所有匹配(X&&Y)
而不是anyMatch(!X | |!Y)
您的错误是,
anyMatch
将返回true
,如果任何条目符合您的条件:
return listOfEntitys.getAll().stream().anyMatch(entity-> !isEntityDateValid(entity.getStartDate())
|| !isEntityDateValid(entity.getEndDate()));
因此,请在此处添加一个非:
return !listOfEntitys.getAll().stream().anyMatch(entity-> !isEntityDateValid(entity.getStartDate())
|| !isEntityDateValid(entity.getEndDate()));
因此,看起来您有一个
for
循环,如果所有日期都有效,它将返回true,如果一个日期无效,它将返回false返回true
不见了,但我想它在那里,否则你最初的翻译就没有意义了
实现这一点的正确方法是使用allMatch()
,这是最准确地传达循环含义的方法:
return listOfEntitys.getAll().stream()
.allMatch(e -> isEntityDateValid(e.getStartDate) || isEntityDateValid(e.getEndDate()));
当且仅当所有实体都具有有效日期时,此选项才会返回true。一旦其中一个无效,它将返回false。就像你的for
循环一样
这还有一个额外的好处,即它避免了负条件,这是代码更干净的规则之一。条件返回语句不能更改为纯流,但如果您向我们展示更多代码,我们可能可以帮助您不需要空检查,因为如果
getAll
返回null,for-each也会失败。
return listOfEntitys.getAll().stream()
.allMatch(e -> isEntityDateValid(e.getStartDate) || isEntityDateValid(e.getEndDate()));