본문 바로가기
Java/기본 문법

Collection 주요 기능 - Map

by 정구정구 2026. 6. 11.

저장, 조회, 삭제

HashMap<String, Integer> map = new HashMap<>();

// 키가 "A"인 값에 1 저장
map.put("A", 1);                     

// "A"키가 없을 때만 10 저장
map.putIfAbsent("A", 10);            

// "B"키 조회, 없으면 기본값 0
int value = map.getOrDefault("B", 0);

// "A"키 존재 여부 확인
boolean isContainKey = map.containsKey("A");

// 값 1 존재 여부 확인
boolean isContainValue = map.containsKey(1);

// Map 크기 확인
int size = map.size();

// 빈 Map인지 확인
boolean isEmpty = map.isEmpty();

// "A"키 삭제
map.remove("A");

// 전체 삭제
map.clear();

 

 

값을 수정하는 다양한 방식

HashMap<String, Integer> scores = new HashMap<>();
scores.put("Kim", 80);

// 일반적인 방식
if (scores.containsKey("Kim")) {
    scores.put("Kim", scores.get("Kim") + 10);
}

// compute (+람다)
scores.compute("Kim", (key, oldVal) -> oldVal + 10);

// 키가 있을 때만 변경
scores.computeIfPresent("Kim", (key, oldVal) -> oldVal + 10);

 

 

순회

HashMap<String, Integer> map = new HashMap<>();
map.put("사과", 1000);
map.put("바나나", 2000);
map.put("오렌지", 3000);

// 1. entrySet() 활용 - (키, 값) 쌍 직접 접근
for (Map.Entry<String, Integer> entry : map.entrySet()) {
    String key = entry.getKey();
    int val = entry.getValue();
    // 처리 로직
}

// 2. keySet() 활용 - 키만 필요할 때
for (String key : map.keySet()) {
    // 키를 이용한 값 조회 또는 처리
}

// 3. values() 활용 - 값만 필요할 때
for (int val : map.values()) {
    // 값만을 이용한 처리
}

 

 

 

응용

// 문제: 같은 길이를 가진 단어들을 그룹화하기
String[] words = {"dog", "cat", "apple", "banana", "rat"};
HashMap<Integer, List<String>> groups = new HashMap<>();

// 방법: computeIfAbsent 사용
for (String word : words) {
    groups.computeIfAbsent(word.length(), k -> new ArrayList<>())
         .add(word);
}
// 결과: {3=[dog, cat, rat], 5=[apple], 6=[banana]}
// 문제: 각 숫자가 처음 나온 위치 기록하기
int[] nums = {1, 2, 3, 1, 2, 1};
HashMap<Integer, Integer> firstPos = new HashMap<>();

// 방법: putIfAbsent 사용
for (int i = 0; i < nums.length; i++) {
    firstPos.putIfAbsent(nums[i], i);
}
// 결과: {1=0, 2=1, 3=2}  // 처음 나온 위치만 저장됨

'Java > 기본 문법' 카테고리의 다른 글

Collection 주요 기능 - List  (0) 2026.06.11
쓰레드(Thread)  (0) 2026.06.11
스트림(Stream)  (0) 2026.06.04
인터페이스(interface)  (0) 2026.06.04
람다(Lambda)  (0) 2026.05.21