首页 > 解决方案 > 将 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;
}
}

标签: javajava-8java-streampredicate

解决方案


不要用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


推荐阅读