Search in sources :

Example 1 with CompoundComparator

use of org.springframework.util.comparator.CompoundComparator in project motech by motech.

the class InMemoryQueryFilter method order.

/**
 * Orders the provided collection using the provided ordering information.
 * @param collection the collection to order
 * @param orderList list of orders that should be applied to the collection
 * @param <T> the type of the collection to order
 * @return a new list with ordered objects from the provided collection
 */
private static <T> List<T> order(Collection<T> collection, List<Order> orderList) {
    List<Comparator<T>> comparatorList = new ArrayList<>();
    for (Order order : orderList) {
        Comparator<T> comparator = new BeanComparator<>(order.getField(), new NullComparator());
        // reverse it if order is descending
        if (order.getDirection() == Order.Direction.DESC) {
            comparator = new ReverseComparator(comparator);
        }
        comparatorList.add(comparator);
    }
    // we use a compound comparator to chain comparators for each provided order
    CompoundComparator<T> compoundComparator = new CompoundComparator<>(comparatorList.toArray(new Comparator[comparatorList.size()]));
    // convert to a list and sort it
    List<T> result = new ArrayList<>(collection);
    Collections.sort(result, compoundComparator);
    return result;
}
Also used : Order(org.motechproject.mds.util.Order) NullComparator(org.apache.commons.collections.comparators.NullComparator) ArrayList(java.util.ArrayList) BeanComparator(org.apache.commons.beanutils.BeanComparator) ReverseComparator(org.apache.commons.collections.comparators.ReverseComparator) CompoundComparator(org.springframework.util.comparator.CompoundComparator) NullComparator(org.apache.commons.collections.comparators.NullComparator) ReverseComparator(org.apache.commons.collections.comparators.ReverseComparator) CompoundComparator(org.springframework.util.comparator.CompoundComparator) BeanComparator(org.apache.commons.beanutils.BeanComparator) Comparator(java.util.Comparator)

Aggregations

ArrayList (java.util.ArrayList)1 Comparator (java.util.Comparator)1 BeanComparator (org.apache.commons.beanutils.BeanComparator)1 NullComparator (org.apache.commons.collections.comparators.NullComparator)1 ReverseComparator (org.apache.commons.collections.comparators.ReverseComparator)1 Order (org.motechproject.mds.util.Order)1 CompoundComparator (org.springframework.util.comparator.CompoundComparator)1