独自クラスを作成してArrayListに入れてソートするサンプルソースおよび実行例を以下に記します。
尚、今回のサンプルソースは固定のメンバ変数をもとにソートするサンプルとなっています。
対象となる複数のメンバー変数があり、処理によりソートキーを指定した場合は、以下のリンクを参照ください。
以下のサンプルソースでは、OperationSystemというクラスを作り、これをArrayListにaddし、
ソートするサンプルソースとなっています。
ソートキーはmarketShareを使用しています。
import java.util.ArrayList;
import java.util.Collections;
class OperationSystem implements Comparable<OperationSystem > {
String productName;
double marketShare;
// constracter
public OperationSystem(String osname, double share) {
this.productName = osname;
this.marketShare = share;
}
public String toString() { // for System.out.println
return this.productName + " : " + this.marketShare + "%";
}
@Override
public int compareTo(OperationSystem o) {
if (o.marketShare < this.marketShare) return 1;
if (o.marketShare > this.marketShare) return -1;
return 0;
}
}
public class OrigListSort {
public static void main(String[] args) {
ArrayList<OperationSystem> osl = new ArrayList<OperationSystem>();
// set data
osl.add(new OperationSystem("Windows 8.1", 3.0D));
osl.add(new OperationSystem("Windows 10", 27.0D));
osl.add(new OperationSystem("Windows XP", 7.0D));
osl.add(new OperationSystem("macOS", 2.0D));
osl.add(new OperationSystem("Windows 7", 49.0D));
osl.add(new OperationSystem("Linux", 1.0D));
System.out.println("-- sort --");
System.out.println("before: " + osl);
Collections.sort(osl);
System.out.println("Collections.sort: " + osl);
System.out.println("-- reverse --");
System.out.println("before: " + osl);
Collections.reverse(osl);
System.out.println("Collections.reverse: " + osl);
}
}
OperationSystemクラスにcompareToメソッド実装しています。
これは、ComparableのcompareToをOverrideしています。
比較し、1, -1, 0を返却しています。
(大きい、小さい、同じを意味しています。)
上記のサンプルソースをコンパイルし、実行した時の出力結果です。
$ javac OrigListSort.java $ java OrigListSort -- sort -- before: [Windows 8.1 : 3.0%, Windows 10 : 27.0%, Windows XP : 7.0%, macOS : 2.0%, Windows 7 : 49.0%, Linux : 1.0%] Collections.sort: [Linux : 1.0%, macOS : 2.0%, Windows 8.1 : 3.0%, Windows XP : 7.0%, Windows 10 : 27.0%, Windows 7 : 49.0%] -- reverse -- before: [Linux : 1.0%, macOS : 2.0%, Windows 8.1 : 3.0%, Windows XP : 7.0%, Windows 10 : 27.0%, Windows 7 : 49.0%] Collections.reverse: [Windows 7 : 49.0%, Windows 10 : 27.0%, Windows XP : 7.0%, Windows 8.1 : 3.0%, macOS : 2.0%, Linux : 1.0%]
使用したJDKのバージョンは以下の通りです。
$ javac -version ; java -version javac 1.8.0_102 java version "1.8.0_102" Java(TM) SE Runtime Environment (build 1.8.0_102-b14) Java HotSpot(TM) Client VM (build 25.102-b14, mixed mode)
ソート・逆ソートされているのが確認できます。
以上、独自(自作)クラスをソート・逆ソートするサンプルソースでした。