import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
// Comparator 클래스 상속 (Comparator -> Interface)
class testComparator implements Comparator<String> {
@Override
public int compare(String a, String b) {
return a.charAt(0) - b.charAt(0);
// charAt(0): 가장 앞에 있는 문자
}
}
public class sortTest {
public static void main(String[] args) {
// 1. Array.sort() 메소드 이용
int [] arr = { 4, 2, 3, 9, 1, 7 };
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
// 내림차순 정렬 -> Collections.reverseOrder() (Primitive 타입은 X)
Integer [] arr2 = { 4, 2, 3, 9, 1, 7 };
Arrays.sort(arr2, Collections.reverseOrder());
System.out.println(Arrays.toString(arr2));
// 2. Collections.sort() 메소드 이용
ArrayList <Integer> arr_list = new ArrayList(Arrays.asList(4, 2, 3, 9, 1, 7));
Collections.sort(arr_list);
System.out.println(arr_list);
// 내림차순
Collections.sort(arr_list, Collections.reverseOrder());
// 3. Comparator 클래스 이용
ArrayList <String> str_list = new ArrayList(Arrays.asList("python", "java", "javascript"));
Collections.sort(str_list, new testComparator());
System.out.println(str_list);
Collections.sort(str_list, new Comparator<String>() {
@Override
public int compare(String a, String b) {
return a.length() - b.length();
}
});
System.out.println(str_list);
// 4. Lambda 이용
ArrayList <Integer> arr_list2 = new ArrayList(Arrays.asList(2, -4, -9, 0, 3, -1, 7));
Collections.sort(arr_list2, (a, b) -> a - b);
System.out.println(arr_list2);
}
}