✨배열 정렬 오름차순
Arrays.sort(arr)
✨배열 내림차순
// 1번
Arrays.sort(arr, Collections.reverseOrder());
// 2번
Arrays.sort(arr, new Comparator<Integer>() {
@Override
public int compare(Integer i1, Integer i2) {
return i2 - i1; // Integer.compare(i2, i1);
}
});
//3번 📢뺄셈은 오버플로의 위험이 있기 때문에 아래 compare메서드를 사용하는 것이 좋다.
Arrays.sort(arr, (i1, i2) -> i2 - i1);
// 4번
Arrays.sort(arr, (i1, i2) -> Integer.compare(i2, i1);
✨✨int[]는 Integer로 바꿔야한다.
🚨🚨int[] -> Integer[]
Integer[] chArr = Arrays.stream(arr).boxed().toArray(Integer[]::new);
✨ int[] 배열 내림차순 정렬 시 Integer배열 전환과 정렬을 한번에
int[] reverse = Arrays.stream(arr).boxed().sorted( (i1, i2) -> i2 - i1 ).mapToInt(Integer::intValue).toArray();
🚨🚨🚨🚨System.out.println(A.compareTo(B)); // A가 더 작으면 음수가 온다.
// 1.
Arrays.sort(arr, (o1, o2) -> o1.compareTo(o2));
// 2.
Arrays.sort( arr, (s1, s2) -> {
if(s1.charAt(1) == s2.charAt(1)) {
return s1.charAt(1) - s2.charAt(2);
}
return s1.compareTo(s2);
});
Arrays.sort( arr, (o1, o2) -> o1.length() - o2.length() )
✨오름차순, 내림차순
Collections.sort(list)
Collcetions.sort(list, Collections.reverseOrder());
String[][] arr = new String[2][2];
// 0의 값으로 정렬하고 싶을 때
Arrays.sort(arr, new Comparator<String[]>(){
@Override
public int compare(String[] o1, String[] o2){
return o1[0].compareTo(o2[0]);
}
});
int classRoom [][] = new int [N][2];
Arrays.sort(classRoom, new Comparator<int[]>() {
@Override
public int compare(int[] arg0, int[] arg1) {
if(arg0[0] == arg1[0]) {
return arg0[1] - arg1[1];
} else {
return arg0[0] - arg1[0];
}
}
});
ArrayList<int[]> list = new ArrayList<>();
for(int n = 0; n < N; n++) {
st = new StringTokenizer(br.readLine(), " ");
int M = Integer.parseInt(st.nextToken());
int P = Integer.parseInt(st.nextToken());
list.add(new int[] {M, P});
}
// 배열[1]에 있는 값부터 내림차순 정렬 시
Collections.sort(list, (o1, o2) -> o2[1] - o1[1]);
// 2. [0]값 기준 오름차순
Collections.sort(list, new Comparator<int[]>(){
@Override
public int compare(int[] a1, int[] a2){
return Integer.compare(a1[0], a2[0]);
}
});
✨ 먼저 실패율을 내림차순 정렬하고 -> 실패율이 같은경우 번호대로 오름차순 정렬할때
맨 마지막 정렬 기준을 먼저 조건문으로 넣어주며 차례로 내려온다.
Collections.sort(list, new Comparator<Node>() {
@Override
public int compare(Node o1, Node o2) {
if(o1.fail == o2.fail)
return Integer.compare(o1.num, o2.num);
return Double.compare(o2.fail, o1.fail);
}
});
✨implements Comparable 인 점이 다르다. (다른 곳 Comparator)
public static class Node implements Comparable<Node>{
@Override
public int compareTo(Node other) {
return Integer.compare(this.num, other.num);
}
}
}