Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

자바(Java)에서 키(Key)를 사용해 HashMap의 값을 업데이트하는 방법

이 글에서는 자바에서 키(key)를 사용하여 HashMap의 값을 업데이트하는 방법을 알아보겠습니다.

자바의 HashMap은 Map 인터페이스를 해시 테이블 기반으로 구현한 자료구조로, 키-값(key-value) 쌍의 모음입니다. 각 키는 고유하며, 키를 통해 저장된 값을 빠르게 조회하거나 수정할 수 있습니다.

예제 개요

먼저 예제의 입력과 기대 출력을 살펴보겠습니다.

입력값:

Input HashMap: {Java=1, Scala=2, Python=3}

기대 출력값:

The HashMap with the updated value is: {Java=1, Scala=12, Python=3}

위 예제에서는 'Scala'라는 키에 해당하는 값 2를 조회한 뒤 10을 더해 12로 업데이트합니다.

알고리즘

전체 과정은 다음 단계로 진행됩니다.

Step 1 - START
Step 2 - 필요한 변수를 선언한다.
Step 3 - 값을 정의한다.
Step 4 - 'put' 메서드를 사용해 HashMap을 생성하고 요소를 초기화한다.
Step 5 - 콘솔에 HashMap을 출력한다.
Step 6 - 'get' 메서드를 사용해 특정 키로 해당 값을 조회한다.
Step 7 - 조회한 값에 원하는 값을 더한다.
Step 8 - 업데이트된 결과를 콘솔에 출력한다.
Step 9 - 종료(STOP)

예제 1: main 함수 안에서 처리하기

첫 번째 예제는 모든 연산을 main 함수 안에서 한 번에 수행하는 방식입니다.

import java.util.HashMap;
public class Demo {
   public static void main(String[] args) {
      System.out.println("The required packages have been imported");
      HashMap<String, Integer> input_map = new HashMap<>();
      input_map.put("Java", 1);
      input_map.put("Scala", 2);
      input_map.put("Python", 3);
      System.out.println("The HashMap is defined as: " + input_map);
      int value = input_map.get("Scala");
      value = value + 10;
      input_map.put("Scala", value);
      System.out.println("\nThe HashMap with the updated value is: " + input_map);
   }
}

실행 결과

The required packages have been imported
The HashMap is defined as: {Java=1, Scala=2, Python=3}

The HashMap with the updated value is: {Java=1, Scala=12, Python=3}

동작 설명:

  • put() 메서드로 세 개의 키-값 쌍을 HashMap에 저장합니다.
  • get("Scala") 메서드로 'Scala' 키에 해당하는 값(2)을 가져옵니다.
  • 가져온 값에 10을 더한 후, 다시 put() 메서드로 같은 키에 새 값을 저장하면 기존 값이 덮어써집니다.

예제 2: 객체 지향 방식으로 함수 분리하기

두 번째 예제는 연산 로직을 별도의 함수로 캡슐화하여 객체 지향 프로그래밍 스타일로 작성한 것입니다.

import java.util.HashMap;
class Demo {
   static void update(HashMap<String, Integer> input_map, String update_string){
      int value = input_map.get(update_string);
      value = value + 10;
      input_map.put("Scala", value);
      System.out.println("\nThe HashMap with the updated value is: " + input_map);
   }
   public static void main(String[] args) {
      System.out.println("The required packages have been imported");
      HashMap<String, Integer> input_map = new HashMap<>();
      input_map.put("Java", 1);
      input_map.put("Scala", 2);
      input_map.put("Python", 3);
      System.out.println("The HashMap is defined as: " + input_map);
      String update_string = "Scala";
      update(input_map, update_string);
   }
}

실행 결과

The required packages have been imported
The HashMap is defined as: {Java=1, Scala=2, Python=3}

The HashMap with the updated value is: {Java=1, Scala=12, Python=3}

추가 팁: merge() 메서드 활용하기

자바 8 이상에서는 merge() 메서드를 사용하면 위 과정을 한 줄로 간결하게 처리할 수 있습니다.

input_map.merge("Scala", 10, Integer::sum);

이 코드는 'Scala' 키가 존재하면 기존 값에 10을 더하고, 존재하지 않으면 10을 새로 저장합니다. 값 업데이트 로직을 더욱 깔끔하게 작성하고 싶다면 merge() 또는 computeIfPresent() 같은 메서드를 활용해 보세요.

마무리

HashMap에서 특정 키의 값을 업데이트하는 핵심 흐름은 'get()으로 값 조회 → 값 수정 → put()으로 재저장'입니다. 두 예제 모두 동일한 결과를 출력하지만, 예제 2처럼 기능을 함수로 분리하면 코드의 재사용성과 유지보수성이 크게 향상됩니다.