Java7まで大活躍してくれたComparatorChain へのお別れブログです。
Java8では本当にソートが楽になりました。
これだけで終わってしまいます。
昇順、降順の組合せもお手軽です。
//テストデータ作成
List<Person> testParsonList = this.createTestDataBeanList();
List<Person> resultParsonList = testParsonList.stream()
.sorted(comparing(Person::getName, nullsLast(reverseOrder()))
.thenComparing(Person::getAge))
.collect(toList());
Java7までは、Apache commonsのComparatorChainで複数のソート項目指定、昇順降順の混在などの複雑なソートを実現していました。
非常にコード量が少なく簡単にソート実現できます。
コードは以下です。
//テストデータ作成
List<Person> testParsonList = this.createTestDataBeanList();
ComparatorChain comparator = new ComparatorChain();
//ソート項目と昇順、降順を指定。
comparator.addComparator(
new BeanComparator<Person>("name",new NullComparator()), true);
comparator.addComparator(
new BeanComparator<Person>("age",new NullComparator()));
//sort実行
Collections.sort(testDataBeanList, comparator);
※どちらもソートクラスにはソート項目分の引数を持ったコンストラクタが必要です。
ソートの種類が複数必要な場合は、ソートの種類によってコンストラクタを増やします。
//※変数定義は省略します。
public Person(final String name, final int age) {
this.name = name;
this.age = age;
}
public Person(final String name, final int age, final address) {
this.name = name;
this.age = age;
this.address = address;
}
public String getName() { return name; }
public int getAge() { return age; }
public int ageDifference(final Person other) {
return age - other.age;
}
public int nameDifference(final Person other) {
return name.compareTo(other.name);
}
必要となるjarは以下です。
- commons-collections-3.2.1.jar
- commons-bean utile-1.9.2.jar
組合せについては、以下を参考にしました。
http://central.maven.org/maven2/commons-beanutils/commons-beanutils/1.9.2/commons-beanutils-1.9.2.pom
あとはこの辺です。
http://mvnrepository.com/artifact/commons-collections/commons-collections/
genericsを使用できるバージョンの組合せは出ていません。
とても残念です。