23
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

複雑なソートを簡単に実現する方法(Java8とそれ以前)

Last updated at Posted at 2015-03-16

Java7まで大活躍してくれたComparatorChain へのお別れブログです。

Java8では本当にソートが楽になりました。
これだけで終わってしまいます。
昇順、降順の組合せもお手軽です。

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で複数のソート項目指定、昇順降順の混在などの複雑なソートを実現していました。
非常にコード量が少なく簡単にソート実現できます。
コードは以下です。

Java7以下
//テストデータ作成
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);

※どちらもソートクラスにはソート項目分の引数を持ったコンストラクタが必要です。
ソートの種類が複数必要な場合は、ソートの種類によってコンストラクタを増やします。

beanの例

  //※変数定義は省略します。

  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を使用できるバージョンの組合せは出ていません。
とても残念です。

23
25
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?