org.opentripplanner.routing.algorithm.filterchain.filters.OtpDefaultSortOrder Maven / Gradle / Ivy
Show all versions of otp Show documentation
package org.opentripplanner.routing.algorithm.filterchain.filters;
import org.opentripplanner.model.plan.Itinerary;
import org.opentripplanner.routing.algorithm.filterchain.ItineraryFilter;
import org.opentripplanner.util.CompositeComparator;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
/**
* This filter will sort the itineraries in OTP default order according to the request
* {@code arriveBy} flag.
*
* The SORT ORDER for a "depart-after-search" is:
*
* - ON-STREET-ONLY before TRANSIT
* - Earliest arrival time first
* - Generalized cost, lowest first
* - Number of transfers, lowest first
* - Latest departure time first
*
*
* The SORT ORDER for a "arrive-by-search" is:
*
* - ON-STREET-ONLY before TRANSIT
* - Latest departure time first
* - Generalized cost, lowest cost first
* - Number of transfers, lowest first
* - Earliest arrival time first
*
*
* The filter do only sort the itineraries, no other modifications are done.
*/
public class OtpDefaultSortOrder implements ItineraryFilter {
/**
* This comparator will sort all itineraries with STREET ONLY first. So, if there is an itinerary
* with walking/bicycle/car from origin all the way to the destination, than it will be sorted
* before any itineraries with one or more transit legs.
*/
static final Comparator STREET_ONLY_FIRST
= (a, b) -> Boolean.compare(b.isOnStreetAllTheWay(), a.isOnStreetAllTheWay());
/** Sort latest arrival-time first */
static final Comparator ARRIVAL_TIME = Comparator.comparing(Itinerary::endTime);
static final Comparator DEPARTURE_TIME = (a, b) -> b.startTime().compareTo(a.startTime());
static final Comparator GENERALIZED_COST = Comparator.comparingInt(a -> a.generalizedCost);
static final Comparator NUM_OF_TRANSFERS = Comparator.comparingInt(a -> a.nTransfers);
private final Comparator sortComparator;
public OtpDefaultSortOrder(boolean arriveBy) {
// Put walking first - encourage healthy lifestyle
sortComparator = new CompositeComparator<>(
STREET_ONLY_FIRST,
arriveBy ? DEPARTURE_TIME : ARRIVAL_TIME,
GENERALIZED_COST,
NUM_OF_TRANSFERS,
arriveBy ? ARRIVAL_TIME : DEPARTURE_TIME
);
}
@Override
public String name() {
return "otp-default-sort-order";
}
@Override
public List filter(List itineraries) {
return itineraries.stream().sorted(sortComparator).collect(Collectors.toList());
}
@Override
public boolean removeItineraries() { return false; }
}