0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Comparatorを使って自在に並べ替える

Posted at

Comparatorとは?

Javaのインターフェースの一つ。Comparatorを実装することで、自分がカスタムした順番でソートすることができるようになります。
例えば、以下の場面で役に立ちます。

  • 複数のフィールドでソートしたい場合
    • 例:顧客リストを年齢、購入額などの順にソート
  • カスタム順序が必要な場合
    • 例:購入額が一定以上の顧客を上位に表示する、最近の購入者を優先的に表示するなど

Comparatorを使ったソート

ここでは、顧客リストを例に出して、Comparatorを使った基本的なソート方法を提示します。

Comparatorの実装

年齢順に並べ替える

import java.util.Comparator;

public class Customer {
    private int age;

    // コンストラクタ、ゲッター、セッターは省略

    public static class AgeComparator implements Comparator<Customer> {
        @Override
        public int compare(Customer c1, Customer c2) {
            return Integer.compare(c1.getAge(), c2.getAge());
        }
   }
}

ソートの実行

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Customer> customers = new ArrayList<>();
        customers.add(new Customer("Alice", 30, 500.0));
        customers.add(new Customer("Bob", 25, 600.0));
        customers.add(new Customer("Charlie", 35, 700.0));

        // 年齢でソート
        Collections.sort(customers, new Customer.AgeComparator());
        // [Customer("Bob", 25, 600.0), Customer("Alice", 30, 500.0), Customer("Charlie", 35, 700.0)]の順に並べ替えられる
    }
}

以下はソートの各ステップを視覚的に示したものです。compareメソッド内で逐一年齢を比較していきます。

初期状態:
[ Alice(30) , Bob(25) , Charlie(35) ]

1. Alice(30)とBob(25)を比較:
   [Bob(25), Alice(30), Charlie(35)]
2. Alice(30)とCharlie(35)を比較:
   [Bob(25), Alice(30), Charlie(35)]
3. Bob(25)とAlice(30)を再度比較:
   [Bob(25) , Alice(30), Charlie(35)]

最終状態:
[ Bob(25) , Alice(30) , Charlie(35) ]
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?