• Home

My Codegate

  • Home

자바 Map 전체 Key, Value 꺼내는 방법

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

public class Sample {

  public static void main(String[] args) {
    HashMap<String, Integer> map = new HashMap<>();
    map.put("A", 1);
    map.put("B", 2);
    map.put("C", 3);

    for (Map.Entry<String, Integer> entry : map.entrySet()) {
      System.out.println(entry.getKey() + " " + entry.getValue());
      // A 1 , B 2 , C 3
    }
    
    map.forEach((key, value) -> System.out.println(key + " " + value));

  }
}

자바에서 Map은 인덱스 기반으로 데이터를 저장하는 게 아니라, Key-value 쌍으로 데이터를 저장하기 때문에 Map에 넣은 값 전부를 뽑아보려면 어떻게 해야하나 싶을텐데

entrySet() 메소드를 사용하면 Map에 들어있는 값을 모두 Set<Entry<Key, Value>> 형식으로 받을 수 있게 되는데 위 반복문과 같이 Map.Entry<Key, Value>로 하나씩 빼주면서, 전체 인덱스를 확인것과 비슷한 방식으로 Map의 전체 Key, Value를 확인할 수 있다

또한 Stream을 사용한다면 forEach를 통해 쉽게 꺼내줄 수 있다.

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