Skip to main content

Map 정렬


1. Map을 키 기준으로 정렬

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

// 키 기준 오름차순 정렬
Map<String, Integer> sortedByKey = new TreeMap<>(map);

2. Map을 값 기준으로 정렬

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

// 값 기준 오름차순 정렬
entries.sort(Map.Entry.comparingByValue());

// 값 기준 내림차순 정렬
entries.sort((a, b) -> b.getValue() - a.getValue());

3. 정렬된 Map 만들기

Map<String, Integer> sortedMap = new LinkedHashMap<>();
for (Map.Entry<String, Integer> entry : entries) {
    sortedMap.put(entry.getKey(), entry.getValue());
}