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;
}
Aggregations