<자료구조>Map 정렬, 순회하기

ming·2023년 4월 4일

자료구조

목록 보기
2/12

HashMap은 정렬되지 않은 순서로 순회한다.
알고리즘 문제를 풀다보면 벨류값을 기준으로 정렬해서 뽑고싶은 순간이 자주 온다!

Map.Entry 리스트를 정렬하여 순회하는 방법

HashMap.entrySet()은 Map의 요소를 Entry 객체로 Set에 저장하고 리턴합니다. 리턴된 Set은 ArrayList 생성자의 인자로 전달하여 리스트로 만들 수 있습니다.

이렇게 만들어진 리스트를 sort()로 정렬하고 for문으로 순회할 수 있다.
아래 예제에서 getValue 대신 getKey로도 가능하다.

예제

import java.util.*;

public class Example1 {

    public static void main(String[] args) {

        Map<String, Integer> map = new HashMap<>();
        map.put("A", 40);
        map.put("C", 20);
        map.put("D", 30);
        map.put("B", 15);

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

        entries.sort(Comparator.comparing(Map.Entry::getValue)); //벨류값을 기준으로 정렬
        for(Map.Entry<String, Integer> entry : entries){
            System.out.println(entry.getValue());
        }
    }
}

출력

15
20
30
40
public class Example1 {

    public static void main(String[] args) {

        Map<String, Integer> map = new HashMap<>();
        map.put("A", 40);
        map.put("C", 20);
        map.put("D", 30);
        map.put("B", 15);

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

        entries.sort(Comparator.comparing(Map.Entry::getValue)); //벨류값을 기준으로 정렬
        for(Map.Entry<String, Integer> entry : entries){
            System.out.println(entry.getKey());
        }
    }
}

출력

B
C
D
A

람다식으로 내림차순으로 정렬하기

벨류값을 기준으로 정렬
List<Map.Entry<String, Integer>> entries = new ArrayList<>(map.entrySet());
entries.sort(((o1, o2) -> map.get(o2.getKey()) - map.get(o1.getKey())));

Map<String, Integer> map = new HashMap<>();
        map.put("A", 40);
        map.put("C", 20);
        map.put("D", 30);
        map.put("B", 15);

        List<Map.Entry<String, Integer>> entries = new ArrayList<>(map.entrySet());
        entries.sort(((o1, o2) -> map.get(o2.getKey()) - map.get(o1.getKey()))); //벨류값을 기준으로 정렬
        for(Map.Entry<String, Integer> entry : entries){
            System.out.println(entry.getKey());
        }
A
D
C
B

TreeMap으로 정렬, 순회

TreeMap은 key값 기준으로 자동 정렬된다. key값만 이용해 정렬된 상태를 만들려면 map을 TreeMap으로 구성하면 된다.

import java.util.Map;
import java.util.TreeMap;

public class Example {

    public static void main(String[] args) {

        Map<String, Integer> map = new TreeMap<>();
        map.put("A", 40);
        map.put("C", 20);
        map.put("D", 30);
        map.put("B", 15);
		
        //스트림출력식
        map.entrySet().forEach(System.out::println);
        System.out.println("---------------");
        //기본적인 keySet()활용
        for(String key : map.keySet()){
            System.out.println(key + "=>" + map.get(key));
        }
        System.out.println("---------------");
        //entrySet()활용
        for(Map.Entry<String, Integer> entry : map.entrySet()){
            System.out.println(entry.getKey() + "->" + entry.getValue());
        }
    }
}
A=40
B=15
C=20
D=30
---------------
A=>40
B=>15
C=>20
D=>30
---------------
A->40
B->15
C->20
D->30

모두 키값 기준으로 자동 정렬된 상태로 출력된다.

profile
개발 성장 기록

0개의 댓글