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

자바(Java) HashMap 요소 반복 방법 – entrySet() 활용 예제


이 글에서는 자바 HashMap에 저장된 요소를 반복(iterate)하며 하나씩 꺼내는 방법을 알아봅니다. 자바 HashMap은 Map 인터페이스를 해시 테이블 기반으로 구현한 자료구조로, 키(key)와 값(value)이 한 쌍을 이루는 엔트리(entry)들의 모음입니다.

먼저 예제에서 사용할 입력과 기대되는 출력 결과를 살펴보겠습니다.

입력 조건 − 프로그램을 실행합니다.

기대 출력

The elements of the HashMap are:
1 : Java
2 : Python
3 : Scala
4 : Javascript

알고리즘

Step 1 - 시작
Step 2 - input_map이라는 이름의 HashMap을 선언합니다.
Step 3 - 키와 값 데이터를 정의합니다.
Step 4 - for 루프로 요소를 반복하면서 getKey()와 getValue() 메서드를 사용해 각 항목의 키와 값을 가져옵니다.
Step 5 - 결과를 화면에 출력합니다.
Step 6 - 종료

예제 1: main 메서드에서 모든 로직 처리하기

첫 번째 예제는 모든 작업을 main 메서드 안에서 한꺼번에 수행하는 방식입니다. 간단한 테스트나 학습용 코드에 적합합니다.

import java.util.HashMap;
import java.util.Map;
public class Demo {
    public static void main(String[] args){
        System.out.println("Required packages have been imported");
        Map<String, String> input_map = new HashMap<String, String>();
        input_map.put("1", "Java");
        input_map.put("2", "Python");
        input_map.put("3", "Scala");
        input_map.put("4", "Javascript");
        System.out.println("A Hashmap is declared\n");
        System.out.println("The elements of the HashMap are: ");
        for (Map.Entry<String, String> set : input_map.entrySet()) {
            System.out.println(set.getKey() + " : " + set.getValue());
        }
    }
}

실행 결과

Required packages have been imported
A Hashmap is declared

The elements of the HashMap are:
1 : Java
2 : Python
3 : Scala
4 : Javascript

예제 2: 객체 지향 방식으로 메서드 분리하기

두 번째 예제는 객체 지향 프로그래밍(OOP) 원칙에 맞게 반복 출력 작업을 별도의 메서드로 분리하여 캡슐화한 방식입니다. 이렇게 구조화하면 코드의 재사용성과 가독성이 크게 향상됩니다.

import java.util.HashMap;
import java.util.Map;
public class Demo {
    static void print(Map<String, String> input_map){
        System.out.println("The elements of the HashMap are: ");
        for (Map.Entry<String, String> set : input_map.entrySet()) {
            System.out.println(set.getKey() + " : " + set.getValue());
        }
    }
    public static void main(String[] args){
        System.out.println("Required packages have been imported");
        Map<String, String> input_map = new HashMap<String, String>();
        input_map.put("1", "Java");
        input_map.put("2", "Python");
        input_map.put("3", "Scala");
        input_map.put("4", "Javascript");
        System.out.println("A Hashmap is declared\n");
        print(input_map);
    }
}

실행 결과

Required packages have been imported
A Hashmap is declared

The elements of the HashMap are:
1 : Java
2 : Python
3 : Scala
4 : Javascript

지금까지 자바 HashMap의 요소를 반복하는 두 가지 방법을 살펴보았습니다. 간단한 코드라면 첫 번째 예제처럼 main 메서드에 모든 로직을 담는 것이 편리하고, 규모가 있는 프로젝트라면 두 번째 예제처럼 기능별로 메서드를 분리하는 것이 유지보수에 유리합니다. 핵심은 entrySet()으로 엔트리 집합을 얻은 뒤, getKey()와 getValue()를 호출해 키와 값을 읽어오는 것입니다.