Java
[Java] HashMap 안의 데이터 확인하기 - HashMap.entrySet()
펜네임
2025. 5. 17. 11:38
Map과 HashMap 의 차이
Map은 인터페이스, HashMap은 Map을 구현한 클래스다.
그래서 HashMap이 Map 형태로 생성된다.
HashMap.keySet()
HashMap.keySet() 메서드를 쓰면 key들이 담긴 바구니를 받는다.
(바구니는 셋 뷰Set View 라고 함)
// Java program to demonstrate the working of keySet()
import java.util.HashMap;
public class Geeks {
public static void main(String[] args) {
// Creating an empty HashMap
HashMap<Integer, String> m = new HashMap<>();
// Adding key-value pairs
m.put(1, "Geeks");
m.put(2, "For");
m.put(3, "Geeks");
m.put(4, "Welcomes");
m.put(5, "You");
// Displaying the HashMap
System.out.println("넣은 값: " + m);
// Using keySet() to get the set view of keys
System.out.println("키: " + m.keySet());
}
}
// 출처 : https://www.geeksforgeeks.org/hashmap-keyset-method-in-java
Output
넣은 값: {1=Geeks, 2=For, 3=Geeks, 4=Welcomes, 5=You}
키: [1, 2, 3, 4, 5]
출력 결과에서 볼 수 있듯이, value 값과 상관없이 key만 보여준다.
HashMap.entrySet()
entrySet()을 쓰면 key와 value를 둘 다 갖춘 데이터들이 바구니에 담긴다.
// Java Program to demonstrate the entrySet() method
import java.util.*;
public class GFG {
public static void main(String[] args) {
// Creating an empty HashMap
HashMap<Integer, String> hm = new HashMap<>();
// Mapping string values to integer keys
hm.put(10, "Geeks");
hm.put(15, "for");
hm.put(20, "Geeks");
hm.put(25, "Welcomes");
hm.put(30, "You");
// Displaying the HashMap
System.out.println("넣은 값: " + hm);
// Using entrySet() to get the set view
System.out.println("키와 밸류 쌍: " + hm.entrySet());
}
}
Output
넣은 값: {Geeks=20, for=15, You=30, Welcomes=25}
키와 밸류 쌍: [Geeks=20, for=15, You=30, Welcomes=25]
이렇게 '키=값' 형태의 데이터를 받을 수 있다.
HashMap.entrySet()을 활용해 데이터 순회하기
일반적으로 entrySet()을 쓰는 이유는 키와 값을 따로 부르기 위해서다.
HashMap<Integer, String> hm = new HashMap<>();
hm.put(1, "엔트리셋에서");
hm.put(2, "데이터");
hm.put(3, "확인하기!");
for (Map.Entry<Integer, String> entry : hm.entrySet()) {
System.out.println(entry.getKey() + " ::: " + entry.getValue());
}
Output
1 ::: 엔트리셋에서
2 ::: 데이터
3 ::: 확인하기!
예제와 같이 Entry.getKey()와 getValue()를 사용한다.