문제
SW Expert Academy
SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!
swexpertacademy.com
풀이
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int t = 1; t <= T; t++) {
System.out.println("#" + t);
int N = sc.nextInt();
sc.nextLine();
HashSet<String> set = new HashSet<>();
for (int i = 0; i < N; i++)
set.add(sc.nextLine());
List<String> arr = new ArrayList<>();
for (String s: set)
arr.add(s);
arr.sort((o1, o2) -> {
if (o1.length() == o2.length())
return o1.compareTo(o2);
return o1.length() - o2.length();
});
arr.stream().forEach(System.out::println);
}
sc.close();
}
}
중복 제거를 위해 우선 HashSet에 문자열을 저장한 뒤 정렬을 위해 List로 옮겼다. (SortedSet을 사용했다면 그럴 필요는 없었을 지도?)
여기서 핵심은 아래 람다식 부분이다.
arr.sort((o1, o2) -> {
if (o1.length() == o2.length())
return o1.compareTo(o2);
return o1.length() - o2.length();
});
- 두 문자열 o1와 o2의 길이를 비교해 짧은 순으로 오름차순 정렬
- 두 문자열 o1와 o2의 길이가 같으면 사전 순으로 오름차순 정렬
참고로 이 람다식을 익명 클래스(Annoymous Class)로 표현하자면 다음과 같다.
arr.sort(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (o1.length() == o2.length()) {
return o1.compareTo(o2);
}
return o1.length() - o2.length();
}
});'PS > SWEA' 카테고리의 다른 글
| SWEA 5658 - 보물상자 비밀번호 [Java] (0) | 2026.08.05 |
|---|---|
| SWEA 3124 - 최소 스패닝 트리 [Java] (0) | 2026.08.04 |
| SWEA 5247 - 연산 [Java][Python] (0) | 2026.07.29 |
| SWEA 1226 - 미로1 [Java] (0) | 2026.07.26 |
| SWEA 2819 - 격자판의 숫자 이어 붙이기 [Java] (0) | 2026.07.25 |