Kotlin은 배열의 정렬을 오름차순과 내림차순 모두 sort()
나 sortDescending()
으로 처리할 수 있는데
Java는 배열에 담는 요소의 자료형이 primitive type
인지 reference type
인지에 따라서 내림차순 방법에 차이가 생긴다.
오름차순은 primitive type과 reference type 모두 Arrays.sort()로 정렬 가능하다.
int[] arr = {3, 2, 6, 4, 8, 7, 1, 5, 9};
Arrays.sort(arr); // {1, 2, 3, 4, 5, 6, 7, 8, 9}
String[] arr = {"carrot", "apple", "banana"};
Arrays.sort(arr); // {"apple", "banana", "carrot"};
내림차순은 오름차순 메소드(Arrays.sort())에 Collections.reverseOrder()
를 매개변수로 추가하면 된다.
String[] arr = {"carrot", "apple", "banana"};
Arrays.sort(arr, Collections.reverseOrder()); // {"carrot", "banana", "apple"};
정렬하기 전에 Primitive type을 Wrapper 클래스로 boxing
하는 과정이 필요하다.
int[] arr = {3, 2, 6, 4, 8, 7, 1, 5, 9};
Integer[] arr2 = Arrays.stream(arr).boxed().toArray(Integer[]::new);
Arrays.sort(arr, Collections.reverseOrder()); // {9, 8, 7, 6, 5, 4, 3, 2, 1}