• Home

My Codegate

  • Home

자바 Map Key 오름차순 내림차순 방법

2023/12/18 Posted by Codegate Java No Comments
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class Sample {

  public static void main(String[] args) {
    Map<String, Integer> unsortedMap = new HashMap<>();
    unsortedMap.put("Banana", 1);
    unsortedMap.put("Apple", 2);
    unsortedMap.put("Orange", 3);

    // 오름차순 정렬
    Map<String, Integer> sortedMap = new TreeMap<>(unsortedMap);
    sortedMap.forEach((key, value) -> System.out.println(key + ": " + value));
    // Apple -> Banana -> Orange

    System.out.println();

    // 내림차순 정렬
    TreeMap<String, Integer> sortedMapDesc = new TreeMap<>(Comparator.reverseOrder());
    sortedMapDesc.putAll(unsortedMap);
    sortedMapDesc.forEach((key, value) -> System.out.println(key + ": " + value));
    // Orange -> Banana -> Apple
  }
}

자바에서 Map의 Key를 가지고 오름차순 내림차순 정렬이 필요할 경우, HashMap의 경우는 기본 key-value 구조로 인덱스 없이 저장하므로 순서 보장이 되지 않지만

TreeMap은 기본적으로 오름차순 정렬을 지원하므로 TreeMap에 넣어놓기만 하면 자동으로 오름차순 정렬이 되고 내림차순 정렬이 필요할 경우에는 선언 시 Comparator.reverseOrder()를 추가해주면 되는데
TreeMap sortedMapDesc = new TreeMap<>(Comparator.reverseOrder());
이런 방식으로 사용한다 마지막으로 TreeMap은 선언 시 오름차순, 내림차순이 고정되기 때문에 사용 전 이걸 주의해주면 되겠다

No Comments
0

Leave a Reply Cancel Reply

Introduction

My Codegate

Latest Posts

  • Google Search Console API 연동방법
  • 인텔리제이 Gradle Dependency 최신 버전 보는 방법
  • Wallet-Tracker 개발일지
  • Moralis API 자바로 호출방법
  • IntelliJ Commit 후 Push 따로 하는 방법

Categories

  • My Project (4)
  • Java (42)
  • Algorithm (161)
    • Java (152)
    • Algorithm Knowledge (3)
    • Algorithm site usage (6)
  • Vue.js (1)
  • Spring (4)
  • Docker (2)
  • IntelliJ (20)
  • Uncategorized (7)

Recent Comments

  • Codegate on Hello world!
  • A WordPress Commenter on Hello world!

© 2025 — mycodegate.com

Prev Next