[ 프로그래머스 ] #42579 : 베스트앨범 - JAVA

🔗 베스트앨범

import java.util.*;
import java.util.stream.*;
class Solution {
    public int[] solution(String[] genres, int[] plays) {
        // genres : 노래의 장르
        // plays : 노래별 재생 횟수


        // 1. 많이 재생된 장르
        // 2. 장르 내에서 많이 재생된 노래
        // 3. 장르 내에서 재생 횟수가 같으면 고유 번호가 낮은 노래 

        // 장르 별로 가장 많이 재생된 노래 2 개씩 순서대로 나열해 return 

        List<Integer> answer=new ArrayList<>();

        // key : genre , value : [고유번호,재생 수]
        Map <String, List<int[]>> genreMap=new HashMap<>();
        // key : genre, value : 총 재생 횟수
        Map <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);

        }

        // 재생 많은 순 정렬
        Stream<Map.Entry<String, Integer>> sortedGenre
            = playMap.entrySet().stream()
                    .sorted((o1,o2)
                        ->Integer.compare(o2.getValue(),o1.getValue()));

        // 각 장르에서 재생 순 정렬하고 2개씩
        sortedGenre.forEach(entry->{
            Stream<int[]>sortedSongs
                =genreMap.get(entry.getKey()).stream()
                    .sorted((o1,o2)->Integer.compare(o2[1],o1[1])).limit(2);

            sortedSongs.forEach(song -> answer.add(song[0]));
        });

        return answer.stream().mapToInt(Integer::intValue).toArray();


    }
}