본문 바로가기
Java

[Java] HashMap을 Value 기준으로 정렬하는 방법

by doongjun 2021. 11. 12.

알고리즘 문제를 풀면서 HashMap을 정렬해야하는 경우가 있었는데 복습할 겸 다시 정리해보려고 한다.

 

HashMap의 Value를 기준으로 정렬하는 함수(sortByValue)를 만들어보자.

 

sortByValue 함수 전체 코드

public static HashMap<String, Integer> sortByValue(HashMap<String, Integer> hm){
    // 1
    List<Map.Entry<String, Integer> > list =
           new LinkedList<Map.Entry<String, Integer>>(hm.entrySet());
    // 2
    Collections.sort(list, new Comparator<Map.Entry<String, Integer> >() {
        public int compare(Map.Entry<String, Integer> o1,
                           Map.Entry<String, Integer> o2)
        {
            return (o1.getValue()).compareTo(o2.getValue());
        }
    });
    // 3
    HashMap<String, Integer> temp = new LinkedHashMap<String, Integer>();
    for (Map.Entry<String, Integer> aa : list) {
        temp.put(aa.getKey(), aa.getValue());
    }
    // 4
    return temp;
}

 

1번부터 차근차근 확인해보면, 아래와 같다.

1. 파라미터로 넘겨받은 HashMap(hm)의 entrySet을 인자로 List를 생성한다.

List<Map.Entry<String, Integer> > list = new LinkedList<Map.Entry<String, Integer>>(hm.entrySet());

2. 생성한 List를 정렬한다.

Collections.sort(list, new Comparator<Map.Entry<String, Integer> >() {
    public int compare(Map.Entry<String, Integer> o1,
                       Map.Entry<String, Integer> o2){
        return (o1.getValue()).compareTo(o2.getValue());
    }
});

※ Comparator에 대해 잘 모른다면 아래 잘 정리되어있는 글을 참고하자.

https://st-lab.tistory.com/243

 

자바 [JAVA] - Comparable 과 Comparator의 이해

아마 이 글을 찾아 오신 분들 대개는 Comparable과 Comparator의 차이가 무엇인지 모르거나 궁금해서 찾아오셨을 것이다. 사실 알고보면 두 개는 그렇게 어렵지 않으나 아무래도 자바를 학습하면서 객

st-lab.tistory.com

3. 정렬된 리스트 데이터를 새로운 HashMap에 삽입한다.

HashMap<String, Integer> temp = new LinkedHashMap<String, Integer>();
for (Map.Entry<String, Integer> aa : list) {
    temp.put(aa.getKey(), aa.getValue());
}

4. 정렬된 HashMap(temp)를 return 해주면 정렬된 HashMap을 확인할 수 있다.

 

잘 동작하는지 확인해보자.

MapSort.java

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class MapSort {
    public static HashMap<String, Integer> sortByValue(HashMap<String, Integer> hm){
        List<Map.Entry<String, Integer> > list =
               new LinkedList<Map.Entry<String, Integer>>(hm.entrySet());

        Collections.sort(list, new Comparator<Map.Entry<String, Integer> >() {
            public int compare(Map.Entry<String, Integer> o1,
                               Map.Entry<String, Integer> o2){
                return (o1.getValue()).compareTo(o2.getValue());
            }
        });

        HashMap<String, Integer> temp = new LinkedHashMap<String, Integer>();
        for (Map.Entry<String, Integer> aa : list) {
            temp.put(aa.getKey(), aa.getValue());
        }
        return temp;
    }

    public static void main(String[] args){
        HashMap<String, Integer> hm = new HashMap<String, Integer>();

        hm.put("수학", 98);
        hm.put("국어", 85);
        hm.put("영어", 91);
        hm.put("과학", 95);
        hm.put("체육", 79);
        hm.put("사회", 80);
        Map<String, Integer> hm1 = sortByValue(hm);

        for (Map.Entry<String, Integer> en : hm1.entrySet()) {
            System.out.println("Key = " + en.getKey() +
                          ", Value = " + en.getValue());
        }
    }
}

결과

 

Lamda를 사용해 정렬
public static HashMap<String, Integer> sortByValue(HashMap<String, Integer> hm){
    // Create a list from elements of HashMap
    List<Map.Entry<String, Integer> > list = new LinkedList<Map.Entry<String, Integer> >(hm.entrySet());

    // Sort the list using lambda expression
    Collections.sort(list, (i1, i2) -> i1.getValue().compareTo(i2.getValue()));

    // put data from sorted list to hashmap
    HashMap<String, Integer> temp = new LinkedHashMap<String, Integer>();
    for (Map.Entry<String, Integer> aa : list) {
        temp.put(aa.getKey(), aa.getValue());
    }
    return temp;
}

 

Stream을 사용해 정렬
public static HashMap<String, Integer> sortByValue(HashMap<String, Integer> hm){
    HashMap<String, Integer> temp
    = hm.entrySet()
          .stream()
          .sorted((i1, i2)
                      -> i1.getValue().compareTo(
                          i2.getValue()))
          .collect(Collectors.toMap(
              Map.Entry::getKey,
              Map.Entry::getValue,
              (e1, e2) -> e1, LinkedHashMap::new));
    return temp;
}

 

출처 : https://www.geeksforgeeks.org/sorting-a-hashmap-according-to-values/

 

Sorting a Hashmap according to values - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

'Java' 카테고리의 다른 글

[Java] 추상클래스와 인터페이스  (0) 2021.11.30
[Java] BufferReader로 입력받기  (0) 2021.11.30
[Java] JRE와 JDK  (0) 2021.07.20
[Java] HashMap 함수 사용하기  (0) 2021.06.16

댓글