我正在尝试将 foreach 转换为流
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()));
}
但我把它搞砸了,因为它总是评估 boolean 值,我只想在它满足条件时返回它
最佳答案
如果您只希望在特定条件下发生返回,您的流命令将需要成为 if
语句的一部分。
if (listOfEntities.getAll()!=null && listOfEntities.getAll().stream().anyMatch(...)) {
return false;
}
但使用 !allMatch(X && Y)
可能比 anyMatch(!X || !Y)
更清楚。
if (listOfEntities.getAll()!=null
&& !listOfEntities.getAll().stream()
.allMatch(entity -> isEntityDateValid(entity.getStartDate())
&& isEntityDateValid(entity.getEndDate()))) {
return false;
}
关于JAVA Foreach 流式传输,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42344256/