✏️ 특정 키에 해당하는 값을 새로운 값으로 변경
1️⃣ put()
put(key, value)
put()
메서드는 HashMap에 키와 값을 추가하는 메서드이지만, key가 이미 존재하는 경우 매핑되는 값이 변경됨
- key가 등록되지 않았다면 null 반환
HashMap<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("A", 2);
2️⃣ replace()
replace(key, value)
- key가 존재하지 않으면 null 반환
HashMap<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.replace("A", 2);
✏️ 특정 키에 해당하는 기존 값을 수정
3️⃣ put()
, get()
HashMap<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("A", map.get("A") * 10);
✏️ 모든 기존 값을 수정
4️⃣ for문, entrySet()
, Map.Entry
HashMap<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
for (Map.Entry<String, Integer> item : map.entrySet()){
item.setValue(item.getValue() * 10);
}
✏️ 특정 조건 만족하는 모든 값 변경
5️⃣ replaceAll()
- Key에 특정 문자열이 포함되는 값만 변경
- 특정 범위에 속하는 Value만 변경하는 상황에서 주로 사용
HashMap<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.replaceAll((key, value) -> {
if(key.contains("A")) {
return value * 10;
}
return value;
});