OptaPlanner添加教师每日工作时长约束代码编译报错求助
OptaPlanner 教师单日工作时长约束问题解决
问题原因
你的代码无法编译是因为OptaPlanner的Constraint Streams API不支持直接在groupBy中使用min()/max(),必须使用ConstraintCollectors工具类提供的聚合收集器方法。另外,你用LocalDate.now()转换LocalTime到EpochSecond的做法存在逻辑问题——应该使用分组对应的日期(即当前教师当天的授课日期),否则会出现日期不匹配的错误。
修正后的代码
import org.optaplanner.core.api.score.stream.ConstraintCollectors; import java.time.ZoneOffset; private Constraint maximumTeacherTimeConstraint(ConstraintFactory constraintFactory) { return constraintFactory.forEach(Lesson.class) .groupBy( Lesson::getTeacher, lesson -> lesson.getBatchTimeSlot().getDate(), ConstraintCollectors.min(lesson -> lesson.getBatchTimeSlot().getStartTime() .toEpochSecond(lesson.getBatchTimeSlot().getDate(), ZoneOffset.UTC) ), ConstraintCollectors.max(lesson -> lesson.getBatchTimeSlot().getEndTime() .toEpochSecond(lesson.getBatchTimeSlot().getDate(), ZoneOffset.UTC) ) ) .filter((teacher, date, minStartTime, maxEndTime) -> maxEndTime - minStartTime > 36000) // 36000秒 = 10小时 .penalize(HardSoftScore.ONE_SOFT) .asConstraint("Teacher daily working time exceeds 10 hours"); }
关键修改点
- 替换聚合函数:将直接的
min()/max()替换为ConstraintCollectors.min()和ConstraintCollectors.max(),这是OptaPlanner约束流API要求的标准聚合方式。 - 修正时间转换逻辑:转换
LocalTime到EpochSecond时,使用当前Lesson对应的BatchTimeSlot的日期,而不是LocalDate.now(),确保时间计算的准确性(避免跨天错误)。 - 优化约束名称:将约束名称改为更清晰的描述,便于后续调试和监控。
内容的提问来源于stack exchange,提问作者user2869612
相关产品推荐
相关产品推荐

