How to convert a for-loop to find the first occurrence to Java streams?

you can do:

allClasses.stream()
          .anyMatch(uc-> (uc.getClassDates().start().before(classEndDate)
                              && uc.getClassDates().end().after(classBeginDate)));

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:

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.


You can use anyMatch in place of 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:

classBooked = allClasses.stream()
                        .map(UniversityClass::getClassDates)
                        .anyMatch(d -> d.start().before(classEndDate) && d.end().after(classBeginDate));