본문 바로가기
카테고리 없음

Map 데이터 정렬하기 _ by Key / by Value

by 찐세 2021. 7. 6.

 

 

Java Map 데이터 정렬하기

 

Map 데이터는 구조적으로 Key - Value의 형태로 값을 저장한다.

 

그렇기 때문에 다른 타입과는 다르게 정렬 기준이 key 또는 value 두가지 이다.

 

 

 

 

 

 

Map 정렬 구현

 

import java.util.*;

public class Test{
    public static void main(String[] args){
        HashMap<String, Integer> map = new HashMap<>();
        map.put("a",19);
        map.put("d",97);
        map.put("c",6);
        map.put("b",10);

        System.out.println("키로 정렬 _ 오름차순");
        sortMapByKey(map, "asc");
        System.out.println("키로 정렬 _ 내림차순");
        sortMapByKey(map, "desc");
        System.out.println("값으로 정렬 _ 오름차순");
        sortMapByValue(map, "asc");
        System.out.println("값으로 정렬 _ 내림차순");
        sortMapByValue(map, "desc");
    }

    private static void sortMapByValue(HashMap<String, Integer> map, String s) {
        List<Map.Entry<String, Integer>> entryList = new ArrayList<>(map.entrySet());

        Collections.sort(entryList, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                if(s.equals("asc")) return o1.getValue().compareTo(o2.getValue()); // 오름차순 정렬
                else if(s.equals("desc"))   return o2.getValue().compareTo(o1.getValue()); // 내림차순 정렬
                else    throw new RuntimeException("정확한 정렬 방식을 입력하세요. acs : 오름차순 , desc : 내림차순");
            }
        });
        entryList.stream().forEach(System.out :: println);
        System.out.println();
    }

    private static void sortMapByKey(HashMap<String, Integer> map, String s) {
        List<String> keyList = new ArrayList<>(map.keySet());
        Collections.sort(keyList, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                if(s.equals("asc")) return o1.compareTo(o2); // 오름차순 정렬
                else if(s.equals("desc"))   return o2.compareTo(o1); // 내림차순 정렬
                else    throw new RuntimeException("정확한 정렬 방식을 입력하세요. acs : 오름차순 , desc : 내림차순");
            }
        });
        keyList.stream().forEach(k -> System.out.printf("%s=%d%n",k,map.get(k)));
        System.out.println();
    }
}

 

 

 

 

결과

 

 

 

Collections.sort( ) 메서드에는 List 타입 밖에 사용을 하지 못하더라!

 

그래서 Map이 아니라 Set 데이터를 정렬하기 위해서도 List 타입으로 변환해서 정렬을 수행해야한다.