Created
January 1, 2020 15:36
-
-
Save KeisukeYamazaki/ec35b85ad7b8366b4405f1fd8a85e4a3 to your computer and use it in GitHub Desktop.
Java 並べ替えの方法
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Comparatorを使えば、ソートのロジック部分を自由に切り替えられる | |
Comparator<User> c1 = new Comparator()<> { | |
public int compare(User o1, User o2) { | |
return Integer.compare(o1.no, o2.no); // 大小比較のロジック部分は自由に記述する | |
} | |
} | |
// Comparatorを単純に逆順にするだけなら、Collections.reverseOrder(Comparator)を使うと楽ちん!! | |
Comparator<User> c2 = Collections.reverseOrder(c1); | |
List<User> users = ...; | |
Collections.sort(users, c1); // 番号昇順でのソート | |
Collections.sort(users, c2); // 番号降順でのソート |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//##複数の条件で大小比較をしたい場合 | |
class User implements Comparable<User> { | |
int no; // 番号 | |
String name; // 氏名 | |
User(int no, String name) { | |
this.no = no; | |
this.name = name; | |
} | |
public int compareTo(User u) { | |
// 先に名前で大小比較をして… | |
int ret = this.name.compareTo(u.name); | |
// 名前で大小の違いがあるならそこで終了 | |
if (ret != 0) { | |
return ret; | |
} | |
// 名前が同じなら番号で比較(降順なので符号を逆にするため -1 を掛ける) | |
return Integer.compare(this.no, u.no) * -1; | |
} | |
public static void main(String[] args) { | |
User u1 = new User(1, "山田太郎"); | |
User u2 = new User(100, "山田太郎"); // 同姓同名! | |
System.out.println(u1.compareTo(u2)); // → 1!! 名前が同じなので番号で判断、1より100の方が大きいが、降順なので「1の方が100より大きい」 | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//##配列(固定長)のソート | |
//#昇順 | |
Arrays.sort(配列名); | |
//#降順 | |
Arrays.sort(配列名, Collections.reverseOrder()); | |
//##Listのソート | |
//#昇順 | |
Collections.sort(リスト名); | |
//#降順 | |
Collections.reverse(リスト名); | |
Collections.sort(リスト名, Collections.reverseOrder()); | |
//##Stream.sorted()でStreamの結果をソートする | |
int[] values = [3,7,1,9,4]; | |
//#昇順 | |
Arrays.stream(values).sorted().forEach(System.out::println); | |
//#降順 | |
Arrays.stream(values).sorted(Collections.reverseOrder()).forEach(System.out::println); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment