3
2

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.

Java オブジェクトのListをソートする

Posted at

#Comparatorを使い、Collections.sort()でソートする

  • Comparatorを使うことで、自分で定義したクラスオブジェクトの特定の値でソートすることができる。
//List<Person> fooというリストを、xフィールドでソート
Collections.sort(
                  foo,
                  new Comparator<Person>() {
                    @Override
                    public int compare(Person obj1, Person obj2){
                      return obj2.getX - obj1.getX;
                       }
                    }
                  );

#Comparator.comparingを使う

  • Comparator.comparingを使うとすっきりと書ける
foo.sort(Comparator.comparing(Person::getX));
3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?