💚 Map 인터페이스
- Map 인터페이스는 Key와 Value의 쌍으로 데이터를 저장하는 자료구조
- Map은 중복된 키를 허용하지 않으며, 각 키는 하나의 값과 매핑된다.
- java.util 패키지에 속해있다.
💚 Map 인터페이스 주요 메서드
반환형 | 메서드 | 설명 |
V | put(K key, V value) | key-value 쌍을 만든 후 map에 넣음 |
V | get(Object key) | key에 매핑되는 value를 리턴. 없으면 null |
V | remove(Object key) | key에 매핑되는 쌍을 제거 |
boolean | containsKey(Object key) | 이 map에 지정된 key가 존재한다면 true반환 |
int | size() | key-value 쌍의 개수를 반환 |
void | clear() | Map에서 모든 데이터 제거 |
- K: key의 타입
- V: value의 타입
💚 Map 인터페이스를 구현한 클래스
- HashMap: 가장 일반적으로 많이 쓰이는 해시 테이블 기반 구현체. 순서를 보장하지 않는다.
- LinkedHashMap: 해시 테이블과 연결 리스트를 조합한 구현체. 순서를 보장한다.
- TreeMap: 이진 검색 트리를 기반으로 한 맵 구현체. 오름차순을 기반으로 정렬한다.
💚 사용 예시
import java.util.HashMap;
import java.util.Map;
public class MapExample {
public static void main(String[] args) {
// HashMap 생성
Map<String, Integer> scores = new HashMap<>();
// 값 추가
scores.put("Alice", 90);
scores.put("Bob", 80);
scores.put("Charlie", 70);
// 값 가져오기
int aliceScore = scores.get("Alice");
System.out.println("Alice's score: " + aliceScore);
// 값 변경
scores.put("Bob", 85);
// 값 삭제
scores.remove("Charlie");
// 맵 크기 확인
System.out.println("Map size: " + scores.size());
// 모든 키-값 쌍 출력
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
String name = entry.getKey();
int score = entry.getValue();
System.out.println(name + "'s score: " + score);
}
}
}
- 출력 결과
Alice's score: 90
Map size: 2
Bob's score: 85
Alice's score: 90
https://docs.oracle.com/javase/8/docs/api/java/util/Map.html
Map (Java Platform SE 8 )
If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null. If the function returns null no mapping is recorded. If the function
docs.oracle.com
'Programming > Java' 카테고리의 다른 글
[Java] 문자열 자르기 (substring) (0) | 2023.04.30 |
---|---|
[Java] ArrayList 오름차순/내림차순 정렬 방법 (0) | 2023.03.30 |
[Java] 다중 for문 탈출하기 (0) | 2023.02.18 |
[Java] 반복문에서 제어의 흐름을 변경하는 break, continue (0) | 2023.01.26 |
[Java] 자바 switch 문 (0) | 2023.01.26 |
댓글