Comparator 연습
import java.util.stream.*;
import java.util.*;
class Solution {
public int[] solution(String[] genres, int[] plays) {
HashMap<String, ArrayList<int[]>> genreMap = new HashMap<>();
HashMap<String, Integer> playMap = new HashMap<>();
for(int i = 0; i< genres.length; i++) {
String genre = genres[i];
int play = plays[i];
if(!genreMap.containsKey(genre)) {
genreMap.put(genre,new ArrayList<>());
playMap.put(genre,0);
}
genreMap.get(genre).add(new int[]{i,play});
playMap.put(genre,playMap.get(genre)+play);
}
ArrayList<Integer> answer = new ArrayList<>();
// // 총 재생 횟수가 많은 장르 순으로 내림차 순 정렬
// Stream<Map.Entry<String, Integer>> sortedGenre = playMap.entrySet().stream()
// .sorted(Comparator.comparing((Map.Entry<String, Integer> entry) -> entry.getValue()).reversed());
// // .sorted(Comparator.comparing(Map.Entry::getValue, Comparator.reverseOrder()));
// sortedGenre.forEach(entry -> {
// Stream<int []> sortedSongs = genreMap.get(entry.getKey()).stream()
// .sorted(Comparator.comparingInt((int[] o) -> o[1]).reversed()
// .thenComparingInt(o -> o[0])
// )
// .limit(2);
// sortedSongs.forEach(song -> answer.add(song[0]));
// });
// return answer.stream().mapToInt(Integer::intValue).toArray();
return playMap.entrySet().stream()
// 1. 장르를 총 재생 횟수 기준으로 내림차순 정렬 (더 간결한 방식)
// .sorted(Comparator.comparing(Map.Entry::getValue, Comparator.reverseOrder()))
.sorted(Comparator.comparing(Map.Entry::getValue).reversed())
// .sorted(Comparator.comparing((Map.Entry<String, Integer> entry) -> entry.getValue()).reversed())
// 2. 각 장르의 상위 2곡 ID를 뽑아 하나의 스트림으로 합침
.flatMapToInt(genreEntry ->
genreMap.get(genreEntry.getKey()).stream()
// 3. 장르 내 노래를 재생 횟수(내림차순), 고유 번호(오름차순)로 정렬
.sorted(Comparator.comparingInt((int[] song) -> song[1]).reversed()
.thenComparingInt(song -> song[0]))
// 4. 상위 2곡만 선택
.limit(2)
// 5. 노래의 고유 ID만 추출하여 IntStream으로 변환
.mapToInt(song -> song[0])
)
// 6. 최종 결과를 int[] 배열로 변환
.toArray();
}
}Last updated