1
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?

More than 3 years have passed since last update.

[java] listのsort

Posted at

javaで配列やlistをsortする方法を集めてみました。自分用メモ。

配列

昇順
int[] array = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8 };
Arrays.sort(array);
降順
Integer[] array = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8 };
Arrays.sort(array, Collections.reverseOrder());

※Collectionsクラスを使用しているため、Integer配列で宣言している。

List

昇順
ArrayList<Integer> al = new ArrayList<>();
al.add(2);
al.add(7);
al.add(1);
al.add(8);
al.add(2);
al.add(8);
Collections.sort(al);
降順
ArrayList<Integer> al = new ArrayList<>();
al.add(2);
al.add(7);
al.add(1);
al.add(8);
al.add(2);
al.add(8);
Collections.sort(al, Collections.reverseOrder());

応用(ユーザ定義クラス、複数値)

応用
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Main {

	public static void main(String[] args) {

		List<Item> itemList = new ArrayList<>();
		itemList.add(new Item(4, "Book", 1000));
		itemList.add(new Item(2, "Bag", 3000));
		itemList.add(new Item(3, "Calendar", 2000));
		itemList.add(new Item(1, "pen", 200));

		// id昇順ソート
		itemList.sort(Comparator.comparing(Item::getId));

		// id降順ソート
		itemList.sort(Comparator.comparing(Item::getId).reversed());

		// kind昇順ソート
		itemList.sort(Comparator.comparing(Item::getKind));

		// kind降順ソート
		itemList.sort(Comparator.comparing(Item::getKind).reversed());

	}
}

class Item {
	int id;
	String kind;
	int price;

	Item(int id, String kind, int price) {

		this.id = id;
		this.kind = kind;
		this.price = price;
	}

	public int getId() {
		return id;
	}

	public String getKind() {
		return kind;
	}

}

1
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
1
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?