11.4 HashMap과 TreeMap
Map은 현실 세계의 "사전(Dictionary)" 과 같은 구조입니다. 단어(Key)를 찾으면 그에 대한 뜻(Value)이 나오는 것처럼, 특정 키(Key)로 값(Value)을 즉시 조회 할 수 있는 것이 Map의 가장 큰 강점입니다.
1. HashMap
가장 많이 쓰이는 Map 구현체입니다. 키(Key)는 중복 불가, 값(Value)은 중복 가능 합니다. 또한 HashSet처럼 저장 순서를 보장하지 않습니다.
import java.util.HashMap;
HashMap<String, Integer> scoreMap = new HashMap<>();
// 1. put(key, value): 데이터 저장
scoreMap.put("국어", 95);
scoreMap.put("수학", 88);
scoreMap.put("영어", 92);
scoreMap.put("과학", 88); // 값(Value)은 중복 가능
// 같은 키로 다시 put하면 기존 값을 덮어씁니다
scoreMap.put("국어", 100);
System.out.println(scoreMap); // {국어=100, 수학=88, 영어=92, 과학=88}
// 2. get(key): 키로 값 조회
System.out.println(scoreMap.get("수학")); // 88
System.out.println(scoreMap.get("체육")); // null (없는 키는 null 반환)
// 3. getOrDefault(): 없는 키는 기본값 반환 (null 방지)
System.out.println(scoreMap.getOrDefault("체육", 0)); // 0
// 4. containsKey(): 키 존재 여부 확인
System.out.println(scoreMap.containsKey("영어")); // true
// 5. remove(key): 특정 키-값 쌍 삭제
scoreMap.remove("과학");
System.out.println(scoreMap.size()); // 3
HashMap 전체 순회 (Entry 활용)
HashMap<String, String> capitals = new HashMap<>();
capitals.put("Korea", "Seoul");
capitals.put("Japan", "Tokyo");
capitals.put("USA", "Washington D.C.");
// entrySet()으로 키-값 쌍을 묶어서 순회
for (HashMap.Entry<String, String> entry : capitals.entrySet()) {
System.out.println(entry.getKey() + "의 수도: " + entry.getValue());
}
// 키만 순회
for (String country : capitals.keySet()) {
System.out.println(country);
}
2. TreeMap
TreeSet처럼, TreeMap은 키(Key)를 기준으로 자동 정렬 해서 보관합니다.
import java.util.TreeMap;
TreeMap<String, Integer> sortedMap = new TreeMap<>();
sortedMap.put("banana", 2);
sortedMap.put("apple", 5);
sortedMap.put("cherry", 1);
// 키(영문명)를 알파벳 순으로 자동 정렬
System.out.println(sortedMap); // {apple=5, banana=2, cherry=1}
// 첫 번째 키, 마지막 키
System.out.println("처음: " + sortedMap.firstKey()); // apple
System.out.println("마지막: " + sortedMap.lastKey()); // cherry
이로써 자바의 3대 컬렉션(List, Set, Map)을 모두 마스터했습니다! 이 세 가지를 잘 선택해서 쓰는 것만으로도 대부분의 실무 데이터 처리 문제를 해결할 수 있습니다.