[ Map ] key값을 기준으로 정렬

1. TreeMap

  • 내부적으로 키를 오름차순 정렬해 유지함
import java.util.Map;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> map = new TreeMap<>();

        map.put("banana", 2);
        map.put("apple", 5);
        map.put("cherry", 3);

        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}
apple: 5
banana: 2
cherry: 3

2. HashMap + Stream API

  • HashMap은 기본적으로 순서를 보장하지 않으므로 정렬된 결과를 얻으려면 LinkedHashMap으로 결과 저장 필요
import java.util.*;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("banana", 2);
        map.put("apple", 5);
        map.put("cherry", 3);

        // 키를 기준으로 정렬
        Map<String, Integer> sortedMap = map.entrySet()
            .stream()
            .sorted(Map.Entry.comparingByKey())
            .collect(Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                (oldValue, newValue) -> oldValue,
                LinkedHashMap::new // 정렬된 순서를 유지하려면
            ));

        sortedMap.forEach((key, value) -> System.out.println(key + ": " + value));
    }
}
apple: 5
banana: 2
cherry: 3

3. Comparator 로 사용자 정의 정렬(내림차순 정렬)

import java.util.*;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("banana", 2);
        map.put("apple", 5);
        map.put("cherry", 3);

        // 사용자 정의 정렬 (내림차순)
        Map<String, Integer> sortedMap = map.entrySet()
            .stream()
            .sorted((e1, e2) -> e2.getKey().compareTo(e1.getKey()))
            .collect(Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                (oldValue, newValue) -> oldValue,
                LinkedHashMap::new
            ));

        sortedMap.forEach((key, value) -> System.out.println(key + ": " + value));
    }
}
cherry: 3
banana: 2
apple: 5

4. TreeMap에 사용자 정의 Comparator 사용

  • TreeMap을 생성할 때 Comparator를 전달하여 키 정렬을 사용자 정의 가능
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Comparator<String> reverseOrder = Comparator.reverseOrder();

        Map<String, Integer> map = new TreeMap<>(reverseOrder);
        map.put("banana", 2);
        map.put("apple", 5);
        map.put("cherry", 3);

        map.forEach((key, value) -> System.out.println(key + ": " + value));
    }
}
cherry: 3
banana: 2
apple: 5

'Java' 카테고리의 다른 글

Comparable (java.lang), Comparator (java.util)  (1) 2025.04.30
Collection 프레임워크  (0) 2025.04.29
JDK, JRE, JVM  (1) 2025.04.22
데이터 타입 분류 - JAVA  (0) 2025.04.20
제어문 - JAVA  (0) 2025.04.15