코딩테스트-알고리즘/문법

[오늘의 자바 문법] HashMap 정렬-2

닉네임생각즁 2024. 1. 14. 19:40

 

이 문제를 풀며 알게 된 내용을 정리한 것이다

https://fruits2lim.tistory.com/entry/%EB%B0%B1%EC%A4%80-BOJSilver-V-1181%EB%B2%88-%EB%8B%A8%EC%96%B4-%EC%A0%95%EB%A0%AC

 

[백준 BOJ/Silver V] 1181번 : 단어 정렬

https://www.acmicpc.net/problem/1181 1181번: 단어 정렬 첫째 줄에 단어의 개수 N이 주어진다. (1 ≤ N ≤ 20,000) 둘째 줄부터 N개의 줄에 걸쳐 알파벳 소문자로 이루어진 단어가 한 줄에 하나씩 주어진다. 주

fruits2lim.tistory.com

 

 

HashMap value 기준 정렬

 

- key 값 기준 오름차순 정렬은 TreeMap으로 가능

- value 값 기준 정렬은 다른걸 이용해줘야함

 

1)

	List<Map.Entry<String, Integer>> entryList = new LinkedList<>(map.entrySet());
        entryList.sort(Map.Entry.comparingByValue()); 
        for(Map.Entry<String, Integer> entry : entryList) {
            entry.getKey();
            entry.getValue();
        }

 

2)

        List<Map.Entry<String, Integer>> entryList = new LinkedList<>(map.entrySet());
        entryList.sort(new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o1.getValue() - o2.getValue();
            }
        });

 

o1.getValue() - o2.getValue() → 오름차순

o2.getValue() - o1.getValue() → 내림차순

 


예시로 알아보자

 

입력

13
but
i
wont
hesitate
no
more
no
more
it
cannot
wait
im
yours

 

코드

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        Map<String, Integer> map = new HashMap<>();
        for(int i=0; i<N; i++) {
            String word = sc.next();
            map.put(word, word.length());
        }
        System.out.println(map);

        List<Map.Entry<String, Integer>> entryList = new LinkedList<>(map.entrySet());
        entryList.sort(new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o1.getValue() - o2.getValue();
            }
        });

        System.out.println("오름차순 정렬 : " + entryList);

        entryList.sort(new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o2.getValue() - o1.getValue();
            }
        });

        System.out.println("내림차순 정렬 : " + entryList);

    }
}

 

 

 

 

 

⭐ value 기준 오름차순 + value 같을때는 key 기준 오름차순

        List<Map.Entry<String, Integer>> entryList = new LinkedList<>(map.entrySet());
        entryList.sort(new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                int comparision = o1.getValue() - o2.getValue();
                return comparision == 0 ? o1.getKey().compareTo(o2.getKey()) : comparision;
            }
        });

        System.out.println("value 기준 오름차순(같은 value 안에서는 key 기준 오름차순)");
        System.out.println(" : " + entryList);