키를 값에 매핑하는 객체로, Map에는 중복 키가 포함될 수 없고 각 키는 최대 하나의 값에 매핑될 수 있다. 따라서 키를 이용하여 값을 검색하거나 저장할 수 있는 구조의 인터페이스다.
키의 순서나 값의 순서를 보장하지 않고 키와 값 모두 null이 될 수 있다.
Map<String, Integer> studentScores = new HashMap<>();
// 추가
studentScores.put("Kim", 95);
studentScores.put("Lee", 85);
studentScores.put("Park", 90);
studentScores.put("Choi", 80);
// 조회 > 95, 85
System.out.println(studentScores.get("Kim"));
System.out.println(studentScores.get("Lee"));
// 수정
studentScores.put("Park", 100);
/* 포함 > Choi가 삭제되었는가?: null
Choi가 삭제되었는가?: false
100점을 맞은 학생이 있는가? true */
studentScores.remove("Choi");
System.out.println("Choi가 삭제되었는가?: "+studentScores.get("Choi"));
System.out.println("Choi가 삭제되었는가?: "+studentScores.containsKey("Choi"));
System.out.println("100점을 맞은 학생이 있는가?: "+studentScores.containsValue(100));
/* 출력 > student: Lee
score: 85
student: Kim
score: 95
student: Park
score: 100 */
for(Map.Entry<String, Integer> entry: studentScores.entrySet()) {
System.out.println("student: " + entry.getKey() + "\nscore: " + entry.getValue());
}