Beanリストを特定フィールドの値でソートする
ジェネリクスを使ったユーティリティメソッドを書いてみた。
org.apache.commons.beanutils.BeanComparatorを用いることで簡潔に記述している。
public static <T> void sort(List<T> beanList, String orderByFieldName, boolean isAsc) { Comparator<T> comparator; if(isAsc) { comparator = new BeanComparator(orderByFieldName); } else { comparator = new BeanComparator(orderByFieldName, new ReverseComparator()); } Collections.sort(beanList, comparator); }
なお、ソートするフィールドの値が null であるような Bean が含まれる場合は、 NullPointerException が発生する。