아이디어
- ArrayList로 x,y 좌표를 받고, Collections.sort 사용하기
package boj_silver.p11650_좌표정렬;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.StringTokenizer;
public class Review1 {
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int N = Integer.parseInt(bf.readLine());
ArrayList<int[]> list = new ArrayList<>(); //arrayList
for (int i =0 ;i<N; i++){
st = new StringTokenizer(bf.readLine());
int x = Integer.parseInt(st.nextToken());
int y = Integer.parseInt(st.nextToken());
//방법1
list.add(new int []{x,y});
}//
Collections.sort(list , (a,b) -> {
if(a[0] ==b[0]){
return a[1] - b[1];
}
return a[0] - b[0];
});
//출력
for (int[] point: list){
System.out.println(point[0] + " " + point[1]);
}
}
}
Collections.sort(list, new Comparator<int[]> {
@Override
public int compare(int[] a, int[] b) {
//x좌표 오름차순, 같으면 y 오름차순
if (a[0] ==b[0]){
return a[1] - b[1];
}
return a[0] - b[0];// x비교
}
}
Collections.sort(list, (a,b) -> {
if(a[0] == b[0]) return a[1] - b[1]; //overflow 방지를 위해 Integer.compare(a[1], b[1]) ;
return a[0]-b[0]
});
Collections.sort(list, (a,b)->
a[0] !=b[0] ? a[0]-b[0] : a[1]-b[1]
);
Collections.sort(list,
Comparator.comparingInt((int[] a) -> a[0]) //x 기준
.thenComparingInt(a-> a[1]) //y 기준
);