설명
Map: 데이터를 보관하는 전체 서랍장
Set: 상자 꾸러미
Map.Entry: Key와 Value 한 쌍이 담겨있는 작은 상자(그리고 이 상자는 Map.Entry라는 인터페이스로 만들어진다.)
Map > Set > Map.Entry
Map에 있는 모든 데이터들을 보고 싶을 때 entrySet() 메소드를 호출하면 Map 서랍장은 안에 들어있는 모든 Map.Entry 상자들을 우리에게 꺼내서 상자 꾸러미(Set) 로 건네준다.
사용법
Map.Entry를 사용하려면 먼저 Map에서 entrySet() 메소드를 호출해서 Map.Entry 객체들의 Set을 얻어와야 한다.
그리고 얻어온 Set<Map.Entry<K, V>> 객체를 반복문으로 돌면서 각 Map.Entry 객체를 하나씩 꺼내서 필요한 작업을 할 수 있다.
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Integer> studentScores = new HashMap<>();
studentScores.put("신짱구", 90);
studentScores.put("신짱아", 85);
studentScores.put("김철수", 95);
for (Map.Entry<String, Integer> entry : studentScores.entrySet()) {
String name = entry.getKey(); //Key 가져오기
Integer score = entry.getValue(); //Value 가져오기
System.out.println(name + "의 점수는 " + score + "점 입니다.");
}
}
}
관련 메서드
getKey(): Map.Entry 객체가 가지고 있는 Key를 반환해준다.
getValue(): Map.Entry 객체가 가지고 있는 Value를 반환해준다.
setValue(V value): Map.Entry 객체의 Value를 새로운 값(value)으로 설정해준다. 이 변경은 Map에도 즉시 반영되고 변경되기 전의 Value 값을 반환해준다.
'Language > JAVA' 카테고리의 다른 글
[JAVA]getOrDefault (1) | 2025.05.16 |
---|---|
[JAVA]InteliJ에서 생성 메뉴 단축키 (0) | 2025.05.11 |
[JAVA]public 클래스명과 파일명 일치 규칙 (0) | 2025.04.22 |
[JAVA]reduce() 메서드 (0) | 2025.02.14 |
[JAVA]Optional 클래스 (0) | 2025.02.10 |