한 걸음 두 걸음

baekjoon 1302 베스트셀러 ] map / key사전순정렬(Treemap자체) 본문

CSE/baekjoon & swexpert

baekjoon 1302 베스트셀러 ] map / key사전순정렬(Treemap자체)

언제나 변함없이 2019. 3. 27. 22:34
반응형
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args){

        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        String empty = sc.nextLine();

        String[] book = new String[n];

        TreeMap<String , Integer> map = new TreeMap<String , Integer>();

        for(int i = 0 ; i < n ; i ++) {
            book[i] = sc.nextLine();
            if(map.containsKey(book[i]))map.put(book[i],map.get(book[i])+1);
            else map.put(book[i],1);
        }

        //맵 Key에 Value 적절하게 넣어놓은 상태
        ValueComparator bvc =  new ValueComparator(map);
        TreeMap<String,Integer> sorted_map = new TreeMap<String,Integer>(bvc);
        sorted_map.putAll(map);
        //출력 
        Iterator<Entry<String, Integer>> it = sorted_map.entrySet().iterator();
        if(it.hasNext()) System.out.println(it.next().getKey());

    }
}
class ValueComparator implements Comparator<String> {

    Map<String, Integer> base;

    public ValueComparator(Map<String, Integer> base) {
        this.base = base;
    }

    @Override
    public int compare(String a, String b) {
        if (base.get(a) > base.get(b)) { //반대로 하면 오름차순 <=
            return -1;
        } else {
            return 1;
        }
    }
}
반응형