Map 인터페이스

Soobin Kim·2024년 4월 6일

Java

목록 보기
35/47

키를 값에 매핑하는 객체로, Map에는 중복 키가 포함될 수 없고 각 키는 최대 하나의 값에 매핑될 수 있다. 따라서 키를 이용하여 값을 검색하거나 저장할 수 있는 구조의 인터페이스다.
키의 순서나 값의 순서를 보장하지 않고 키와 값 모두 null이 될 수 있다.

구현 클래스

  • HashMap
    해시 테이블을 사용하여 요소를 저장하며 순서를 보장하지 않는다.
  • TreeMap
    키의 순서를 정렬하여 저장하며, 이진 검색 트리를 사용한다.
  • LinkedHashMap
    해시 테이블과 연결 리스트를 사용하여 요소를 저장하며 삽입 순서를 보장한다.

Docs


주요 메서드 예시

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());
}

0개의 댓글