💡풀이 1
- Comparator 람다식 활용
import java.util.*;
class Solution {
public String[] solution(String[] strings, int n) {
Arrays.sort(strings, (s1, s2)->{
int result = Character.compare(s1.charAt(n), s2.charAt(n));
if(result == 0){
result = s1.compareTo(s2);
}
return result;
});
return strings;
}
}
💡풀이 2
- Comparator 메서드 체이닝 사용 (람다식 보다 권장)
import java.util.Arrays;
import java.util.Comparator;
class Solution {
public String[] solution(String[] strings, int n) {
Arrays.sort(strings, Comparator
.comparing((String s) -> s.charAt(n))
.thenComparing(s -> s)
);
return strings;
}
}
💡풀이 3
- 기준이 되는 값을 문자열 앞에 붙이고 그대로 정렬
import java.util.*;
class Solution {
public String[] solution(String[] strings, int n) {
return Arrays.stream(strings)
.map(e -> e.charAt(n) + e)
.sorted()
.map(equals -> equals.substring(1))
.toArray(String[]::new);
}
}
📖새로 배운 부분
Stream에서
- toArray()만 쓰면 Object [] 반환
- toArray(String []::new)를 쓰면 String[] 반환
- String []::new는 메서드 참조로 size -> new String [size]와 동일
+
- 자바 문자열 정렬 관련 내용을 글로 정리해 두었습니다!!
- effective java 책 요약
[EffectiveJava] Item 14. Comparable을 구현할지 고려하라
Comparable특정 클래스의 인스턴스들 간에 순서를 정할 수 있는 기준을 제공합니다.compareTo라는 유일한 메서드를 구현해야 합니다.자연스러운 순서(natural order)가 있는 값들(예: 숫자, 문자열, 날짜
devoks.tistory.com
GitHub - okjunghyeon/Programmers_CodingTest: 프로그래머스 관련 코딩테스트 문제를 풀이한 저장소입니다.
프로그래머스 관련 코딩테스트 문제를 풀이한 저장소입니다. Contribute to okjunghyeon/Programmers_CodingTest development by creating an account on GitHub.
github.com
'CodingTest > Programmers' 카테고리의 다른 글
[프로그래머스, Java] 카드 뭉치 (0) | 2025.07.15 |
---|---|
[프로그래머스, Java] 명예의 전당 (1) (0) | 2025.07.15 |
[프로그래머스, Java] 콜라 문제 (0) | 2025.07.15 |
[프로그래머스, Java] K번째수 (0) | 2025.07.15 |
[프로그래머스, Java] 숫자 문자열과 영단어 (0) | 2025.07.15 |