1. 程式人生 > >基於泛型實現ArrayList的複合排序

基於泛型實現ArrayList的複合排序

最近專案中經常要對list進行復合排序;每一次排序需求都不一樣,需要些特定的排序方法。而基於泛型的複合排序方法能很好的避免了程式碼的重複。

public class SortUtil {

	@SuppressWarnings("unchecked")
	public static <T> void sortEntityByFields(List<T> entities, String... params) {

		Comparator<T> comparator = ComparableComparator.getInstance();

		// reverses the order of the input comparator
		// comparator = ComparatorUtils.reversedComparator(comparator);
		// allows nulls, the null value greater than nonnull value
		// comparator = ComparatorUtils.nullLowComparator(comparator);

		List<BeanComparator> beanComparators = new ArrayList<BeanComparator>();
		for (String param : params) {
			beanComparators.add(new BeanComparator(param, comparator));
		}

		ComparatorChain comparatorChain = new ComparatorChain(beanComparators);
		Collections.sort(entities, comparatorChain);
	}
}