java - 将 BiPredicate 传递给 Stream 以比较对象列表
问题描述
如果行程时间表不重叠,行程列表只能由一个人完成。例如,这个列表应该返回 true,因为日期不重叠。
Journey 1: "2019-09-10 21:00" --> "2019-09-10 21:10"
Journey 2: "2019-08-11 22:10" --> "2019-08-11 22:20"
Journey 3: "2019-09-10 21:30" --> "2019-09-10 22:00"
我创建了一个谓词来检查旅程时间是否重叠。我想在流中使用这个 BiPredicate。解决这个问题的正确方法是什么?
public class Journey {
public static void main(String[] args) throws Exception {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("y-M-d H:m");
ArrayList<Route> routes = new ArrayList<>();
// This example should return true because there is no overlap between the routes.
routes.add(new Route(simpleDateFormat.parse("2019-09-10 21:00"), simpleDateFormat.parse("2019-09-10 21:10")));
routes.add(new Route(simpleDateFormat.parse("2019-08-11 22:10"), simpleDateFormat.parse("2019-08-11 22:20")));
routes.add(new Route(simpleDateFormat.parse("2019-09-10 21:30"), simpleDateFormat.parse("2019-09-10 22:00")));
boolean result = travelAllRoutes(routes);
System.out.println(result);
}
public static boolean travelAllRoutes(List<Route> routes) {
BiPredicate<Route, Route> predicate = (r1, r2) -> r1.getEndJourney().before(r2.getStartJourney());
// boolean result = routes.stream(); // use predicate here
return result;
}
}
class Route {
private Date startJourney, endJourney;
public Route(Date startJourney, Date endJourney) {
this.startJourney = startJourney;
this.endJourney = endJourney;
}
public Date getStartJourney() {
return startJourney;
}
public void setStartJourney(Date startJourney) {
this.startJourney = startJourney;
}
public Date getEndJourney() {
return endJourney;
}
public void setEndJourney(Date endJourney) {
this.endJourney = endJourney;
}
}
解决方案
不要用Stream
这里没有用,简单for-loop
就是完美
public static boolean travelAllRoutes(List<Route> routes) {
Route lastRoute = null;
routes.sort(Comparator.comparing(Route::getStartJourney));
for (Route r : routes) {
if (lastRoute == null) {
lastRoute = r;
continue;
}
if (lastRoute.getEndJourney().after(r.getStartJourney()))
return false;
lastRoute = r;
}
return true;
}
}
我也建议使用java.time.LocalDate
而不是旧的java.util.Date
推荐阅读
- sql - 将相同的金额组合在一起,但在不同的列中找到不同的金额
- tensorflow - 无法使用 RectifiedAdam 优化器加载 Keras 模型
- android - ReactNative 使用 Android Studio 添加 Gradle 依赖
- statistics - 对变量的每个类别分别运行分析
- javascript - 如何映射函数和文本 ReactJs
- reactjs - 如何在 Redux 中制作受控输入组件?
- bower - bash: bower: NVM 找不到命令
- javascript - 合并2个对象在js中包括他们的孩子
- html - 如何根据使用 CSS 对嵌套输入的关注来更改分隔 div 的颜色?
- html - IE 搜索文本功能不适用于从 AJAX 生成的代码