2
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 3 years have passed since last update.

Collectionsインターフェースを利用してListを並び替える方法

Posted at

Collectionsインターフェースを利用してListを並び替える方法

今回はCollectionsインターフェースを利用してListを並び替える方法を紹介させて頂きます。


Comparatorインターフェースを利用して並び替える場合

基本データ型が入ったList内の要素を昇順で並び替える場合は
Collections.sort(List);
降順で並び替える場合は
Collections.sort(List,Collections.reverseOrder());
を使用することでList内の要素を並び替える事ができますが
オブジェクト(インスタンス)が入ったListをインスタンス変数を参照して並び替えるにはComparatorインターフェースのcompareメソッドを実装したクラスを自分で実装し、利用する必要があります。
実際にCompareメソッドを実装し、利用してみたコードがこちらです。

class Fruit {
	private String name;
	private Integer price;
	public Fruit(String name,Integer price) {
		this.name = name;
		this.price = price;
	}
	public String getName() { return this.name; }
	public Integer getPrice() { return this.price; }
}

//インスタンス変数nameの昇順で並び替えを行う
class nameComparator implements Comparator<Fruit> {
	public int compare(Fruit fruit1,Fruit fruit2) {
		return fruit1.getName().compareTo(fruit2.getName());
	}
}

//インスタンス変数priceの昇順で並び替えを行う
class priceComparator implements Comparator<Fruit> {
	public int compare(Fruit fruit1,Fruit fruit2) {
		return fruit1.getPrice().compareTo(fruit2.getPrice());
	}
}

public class Main {
	public static void main(String[] args) {
		List<Fruit> fruitList = new ArrayList<>();
		//fruitListにFruitオブジェクトを追加
		fruitList.add(new Fruit("Orange",800));
		fruitList.add(new Fruit("Melon",2000));
		fruitList.add(new Fruit("Apple",300));
		fruitList.add(new Fruit("Grape",500));

		System.out.println("fruitListの中身");
		print(fruitList);
		System.out.println("");
		System.out.println("fruitListの中身(nameComparatorを利用してsort後)");
		Collections.sort(fruitList,new nameComparator());
		print(fruitList);
		System.out.println("");
		System.out.println("fruitListの中身(priceComparatorを利用してsort後)");
		Collections.sort(fruitList,new priceComparator());
		print(fruitList);

	}
	//List<Fruit>の要素のインスタンス変数を出力するメソッド
	public static void print(List<Fruit> fruitList) {
		for(Fruit fruit : fruitList) {
			System.out.println(fruit.getName() + " " + fruit.getPrice());
		}
	}
}

実行結果

fruitListの中身
Orange 800
Melon 2000
Apple 300
Grape 500

fruitListの中身(nameComparatorを利用してsort後)
Apple 300
Grape 500
Melon 2000
Orange 800

fruitListの中身(priceComparatorを利用してsort後)
Apple 300
Grape 500
Orange 800
Melon 2000

Fruitオブジェクトのname変数やprice変数の昇順で並び替える事ができました。
降順で並び替える際は以下の様にcompareメソッド内で使用されているcompareToの引数を逆にして実装します。

//昇順の場合
return fruit1.getPrice().compareTo(fruit2.getPrice());
//降順の場合
return fruit2.getPrice().compareTo(fruit1.getPrice());

ラムダ式を利用してComparatorインターフェースを実装してみる

Comparatorインターフェースの実装を上記のコードのように実装してしまうとコードが長くなりやすく、ラムダ式を利用して実装する事で短くまとまったコードになるためより良いと思います。
ラムダ式を利用してコードを書き直した場合。

class Fruit {
	private String name;
	private Integer price;
	public Fruit(String name,Integer price) {
		this.name = name;
		this.price = price;
	}
	public String getName() { return this.name; }
	public Integer getPrice() { return this.price; }
}

public class Main {
	public static void main(String[] args) {
		List<Fruit> fruitList = new ArrayList<>();
		//fruitListにFruitオブジェクトを追加
		fruitList.add(new Fruit("Orange",800));
		fruitList.add(new Fruit("Melon",2000));
		fruitList.add(new Fruit("Apple",300));
		fruitList.add(new Fruit("Grape",500));

		System.out.println("fruitListの中身");
		print(fruitList);
		System.out.println("");
		System.out.println("fruitListの中身(name変数でsort後)");
		Collections.sort(fruitList,(fruit1,fruit2) -> fruit1.getName().compareTo(fruit2.getName()));
		print(fruitList);
		System.out.println("");
		System.out.println("fruitListの中身(price変数でsort後)");
		Collections.sort(fruitList,(fruit1,fruit2) -> fruit1.getPrice().compareTo(fruit2.getPrice()));
		print(fruitList);

	}
	//List<Fruit>の要素のインスタンス変数を出力するメソッド
	public static void print(List<Fruit> fruitList) {
		for(Fruit fruit : fruitList) {
			System.out.println(fruit.getName() + " " + fruit.getPrice());
		}
	}
}

実行結果はラムダ式を使用せずに記述した場合と同じなので割愛します。
ラムダ式を利用することでComparatorインターフェイスの実装が短くまとまりました。


まとめ

  • オブジェクトを入れたListを並び替える場合はComparatorインターフェースの実装クラスを作成し、sortメソッドで利用する。
  • ラムダ式を利用することでComparatorの実装を短くまとめられる。
2
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
2
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?