"2019-09-10 21:10"-6ren">
gpt4 book ai didi

java - 将 BiPredicate 传递给 Stream 以比较对象列表

转载 作者:行者123 更新时间:2023-12-02 09:36:45 25 4
gpt4 key购买 nike

如果旅程时间表不重叠,则旅程列表只能由一个人完成。例如该列表应返回 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循环就完美了

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

关于java - 将 BiPredicate 传递给 Stream 以比较对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57444326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com