Map 정렬

김하영·2023년 3월 30일
0

자바 쫌쫌따리

목록 보기
3/5

java에서 프로그래밍을 하다 보면 HashMap에서 정렬이 필요할 때가 있다.

key나 value를 기준으로 정렬하는 방법에 대해 알아보자!

TreeMap클래스를 쓰면 key를 기준으로 오름차순 정렬을 해준다!

key 순서대로 정렬 - 오름차순

  1. map의 keySet을 따로 (배열이나 리스트로)가져와 key를 기준으로 정렬한다.
  2. 정렬된 keySet순서대로 데이터를 불러온다.
// keySet을 list로 가져와 정렬하기
public class Main {

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

        map.put(1, "A");
        map.put(2, "B");
        map.put(3, "C");
        
				/**********/
        List<Integer> keys = new ArrayList<>(map.keySet());
        keys.sort((x, y)->x-y);
//      keys.sort((x, y)->y-x); //  내림차순
				/**********/

        for(Integer key : keys){
            System.out.println("key: " + key+" value: "+map.get(key));
        

    }
}
// keySet을 배열로 가져와 정렬하기
public class Main {
    public static void main(String[] args) {
        HashMap<Integer, String> map = new HashMap<>();

        map.put(1, "A");
        map.put(2, "B");
        map.put(3, "C");
		
				/**********/
        Integer[] keys = map.keySet().toArray(new Integer[0]);
        Arrays.sort(keys);
//      Arrays.sort(keys, (x, y)->y-x); // 내림차순

				/**********/

        for(Integer key : keys){
            System.out.println("key: " + key+" value: "+map.get(key));
        }

    }
}
//결과
key: 1 value: A
key: 2 value: B
key: 3 value: C

// 내림차순 결과
// 결과
key: 3 value: C
key: 2 value: B
key: 1 value: A

value 순서대로 정렬

  1. map.keySet()을 리스트로 가져온다.
  2. 가져온 리스트를 value를 기준으로 정렬한다.
  3. 정렬된 key의 순서대로 값을 호출하며 출력한다.
// keySet()을 사용하여 정렬
public class Main {

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

        map.put(30, "A");
        map.put(20, "B");
        map.put(100, "C");

        List<Integer> keySet = new ArrayList<>(map.keySet());
        keySet.sort((x, y)-> map.get(x).compareTo(map.get(y)));
//      keySet.sort((x, y)-> map.get(y).compareTo(map.get(x))); // 내림차순
        
        for(Integer key : keySet){
            System.out.println("key: "+key+" value: "+map.get(key));
        }
}
  1. map.entrySet()을 리스트로 만든다.
  2. Collections.sort()를 사용하여 만든 리스트를 value를 기준으로 정렬한다.
  3. 정렬된 entrySet에서 key와 value를 출력한다.
// entrySet을 사용하여 정렬
public class Main {

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

        map.put(30, "A");
        map.put(20, "B");
        map.put(100, "C");

        List<Map.Entry<Integer, String>> entrySet = new ArrayList<>(map.entrySet());

        Collections.sort(entrySet, new Comparator<Map.Entry<Integer, String>>() {
            @Override
            public int compare(Map.Entry<Integer, String> o1, Map.Entry<Integer, String> o2) {
                return o1.getValue().compareTo(o2.getValue());
//  						return o2.getValue().compareTo(o1.getValue()); // 내림차순
            }
        });

        for(Map.Entry<Integer, String> entry : entrySet){
            System.out.println("key: " + entry.getKey()+" value: "+entry.getValue());
        }

    }
// 결과
key: 30 value: A
key: 20 value: B
key: 100 value: C

// 내림차순 결과
key: 100 value: C
key: 20 value: B
key: 30 value: A

참고자료

https://woovictory.github.io/2020/11/10/Map-Sort/

https://ponyozzang.tistory.com/404

profile
백엔드 개발자로 일하고 싶어요 제발

0개의 댓글