チュートリアル
Java で配列として格納した値を昇順、降順にソートするサンプルをご紹介します。
サンプルコード:配列を昇順にソートする
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | import java.util.ArrayList; import java.util.Collections; public class ListSortAsc { 	public static void main(String[] args) { 		ArrayList<String> animalList = new ArrayList<String>(); 		// 配列に値を追加 		animalList.add("dog");		// いぬ 		animalList.add("rabbit");	// うさぎ 		animalList.add("cow");		// うし 		animalList.add("horse");	// うま 		animalList.add("fox");		// きつね 		animalList.add("giraffe");	// きりん 		animalList.add("bear");		// くま 		animalList.add("gorilla");	// ごりら 		animalList.add("monkey");	// さる 		animalList.add("elephant");	// ぞう 		animalList.add("cat");		// ねこ 		// リストをそのまま出力 		System.out.println("----- リストをそのまま出力 -----"); 		for (String animal : animalList) { 			System.out.println(animal); 		} 		// 配列をソート(昇順) 		Collections.sort(animalList); 		// ソート後を出力(昇順) 		System.out.println("----- ソート後を出力(昇順) -----"); 		for (String animal : animalList) { 			System.out.println(animal); 		} 	} } | 
実行結果
格納した値が昇順で出力されることが確認できました。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | ----- リストをそのまま出力 ----- dog rabbit cow horse fox giraffe bear gorilla monkey elephant cat ----- ソート後を出力(昇順) ----- bear cat cow dog elephant fox giraffe gorilla horse monkey rabbit | 
サンプルコード:配列を降順にソートする
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | import java.util.ArrayList; import java.util.Collections; public class ListSortDesc { 	public static void main(String[] args) { 		ArrayList<String> animalList = new ArrayList<String>(); 		// 配列に値を追加 		animalList.add("dog");		// いぬ 		animalList.add("rabbit");	// うさぎ 		animalList.add("cow");		// うし 		animalList.add("horse");	// うま 		animalList.add("fox");		// きつね 		animalList.add("giraffe");	// きりん 		animalList.add("bear");		// くま 		animalList.add("gorilla");	// ごりら 		animalList.add("monkey");	// さる 		animalList.add("elephant");	// ぞう 		animalList.add("cat");		// ねこ 		// リストをそのまま出力 		System.out.println("----- リストをそのまま出力 -----"); 		for (String animal : animalList) { 			System.out.println(animal); 		} 		// 配列をソート(降順) 		Collections.sort(animalList, Collections.reverseOrder()); 		// ソート後を出力(降順) 		System.out.println("----- ソート後を出力(昇順) -----"); 		for (String animal : animalList) { 			System.out.println(animal); 		} 	} } | 
実行結果
格納した値が降順で出力されることが確認できました。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | ----- リストをそのまま出力 ----- dog rabbit cow horse fox giraffe bear gorilla monkey elephant cat ----- ソート後を出力(昇順) ----- rabbit monkey horse gorilla giraffe fox elephant dog cow cat bear | 
ソートを行うポイント
並べかえる場合には、Collectionsクラスのsort関数を使います。
| 1 2 | // 配列を昇順で並び替え Collections.sort(ArrayListオブジェクト); | 
| 1 2 | // 配列を降順で並び替える(引数にCollections.reverseOrder()を指定します) Collections.sort(ArrayListオブジェクト, Collections.reverseOrder()); | 
