[英]How to convert a for-loop to find the first occurrence to Java streams?
I have the following code that is functionally working我有以下功能正常的代码
for (UniversityClass class : allClasses)
{
Period<Date> classDate = class.getClassDates();
if (classDate.start().before(classEndDate)
&& classDate.end().after(classBeginDate))
{
classBooked = true;
break;
}
}
I have tried this:我试过这个:
allClasses.stream().filter(class -> {
Period<Date> classDate = class.getClassDates();
if (classDate.start().before(classEndDate)
&& classDate.end().after(classBeginDate))
return true;
}).findFirst().ifPresent($ -> {
classBooked = true;
});
But this throws to add a return statement.但这会引发添加返回语句。 Also, the
classBooked
variable needs to be declared final, but that cannot be done.此外,
classBooked
变量需要声明为 final,但不能这样做。 What is the mistake being done?正在做的错误是什么?
Also, once true, I need to break
from it.此外,一旦属实,我需要
break
它。 that is why I thought of adding findFirst().ifPresent()这就是为什么我想添加 findFirst().ifPresent()
To fix the specific problems in your code, your lambda always needs to return a value, and the ifPresent
needs to be changed to isPresent
:要修复代码中的特定问题,您的 lambda始终需要返回一个值,并且需要将
ifPresent
更改为isPresent
:
final boolean classBooked = allClasses.stream()
.filter(c -> {
final Period<Date> classDate = c.getClassDates();
return classDate.start().before(classEndDate)
&& classDate.end().after(classBeginDate)
})
.findFirst().isPresent();
However , anyMatch
, as shown in the other answers, is a better solution.但是,如其他答案所示,
anyMatch
是更好的解决方案。
You can use anyMatch
in place of filter
, findFirst
:您可以使用
anyMatch
代替filter
, findFirst
:
classBooked = allClasses.stream()
.anyMatch(c -> {
Period<Date> classDate = c.getClassDates();
return (classDate.start().before(classEndDate) && classDate.end().after(classBeginDate));
});
You may also use map
to be slightly more readable:您也可以使用
map
来提高可读性:
classBooked = allClasses.stream()
.map(UniversityClass::getClassDates)
.anyMatch(d -> d.start().before(classEndDate) && d.end().after(classBeginDate));
you can do:你可以做:
allClasses.stream()
.anyMatch(uc-> (uc.getClassDates().start().before(classEndDate)
&& uc.getClassDates().end().after(classBeginDate)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.