[英]JAVA Foreach to Stream
我正在尝试将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()));
}
但我搞砸了,因为它总是评估布尔值,我只想在满足条件时返回它
如果您只希望在某些条件下返回,则您的stream命令将需要成为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;
}
你的错误是如果任何条目符合你的条件, 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 。
return true
是丢失但我想它就在那里,否则你的初始翻译将没有意义。
实现这个的正确方法是使用allMatch()
,这是最准确地传达循环含义的方法:
return listOfEntitys.getAll().stream()
.allMatch(e -> isEntityDateValid(e.getStartDate) || isEntityDateValid(e.getEndDate()));
当且仅当所有实体都有有效日期时,这将返回true。 只要一个无效,它就会返回false。 就像你的for
循环一样。
这还有一个额外的好处,它可以避免负面条件 ,这是具有更清晰代码的规则之一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.