중복된 값을 제거하기 위해 HashSet에 입력을 받고, 이를 다시 ArrayList에 담는다.
이후 Collection의 Comparator를 오버라이딩 해 주어진 조건 대로 정렬을 수행한다.
풀이
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int N = Integer.parseInt(br.readLine());
Set<String> set = new HashSet<>();
// 입력을 받을 때마다 Set에 추가해 중복을 제거
for(int i=0; i<N; i++) {
set.add(br.readLine());
}
// Collection의 정렬 메서드를 사용하기 위해 ArrayList에 다시 저장
List<String> list = new ArrayList<>(set);
// Comparator 재구현
list.sort((n1, n2) -> {
// 길이가 다르다면 길이 순으로
if(n1.length() != n2.length()) {
return n1.length() - n2.length();
}
// 아니면 사전 순으로 정렬
return n1.compareTo(n2);
});
for(String l: list) {
sb.append(l).append('\n');
}
System.out.println(sb);
}
}