카테고리 없음

[Java]HashMap 쓰는 방법 - 써야 하는 경우 정리

niahh 2025. 5. 11. 11:26

HashMap은 Map 인터페이스를 구현한 클래스이다. 

 

키- 값 쌍 을 저장할 수 있도록하는 자료구조이고, 빠른 검색, 저장, 삭제가 필요한 경우에 사용된다.

 

시간 복잡도가 O(1)로 검색 속도가 매우 빠르다. 

 

HashMap 대표 함수들

package HashMap;

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {

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

        // 키 - 값 기반 저장
        map.put("apple", 3);
        map.put("banana", 2);
        map.put("orange", 1);
        map.put("pineapple", 1);
        System.out.println(map);

        // 값 조회 (get)
        int count = map.get("apple");
        System.out.println(count);

        // 키 존재 여부 확인 (containsKey)
        boolean hasBanana = map.containsKey("banana");
        System.out.println(hasBanana);

        map.remove("orange");

        // 전체 크기 (size)
        System.out.println(map.size());

        // 전체 반복 (entrySet)
        for (HashMap.Entry<String, Integer> entry : map.entrySet()) {

            System.out.println(entry.getKey() + " " + entry.getValue());

        }


    }
}

 

HashMap을 사용하는 구체적 상황

 

1. 복잡한 조건 분기나 매핑이 필요한 경우 (HTTP 코드 : 의미) 

 

Map<Integer, String> statusMap = Map.of (
        200, "OK", 
        404, "Not Found", 
        500, "Server Error"
);

 

2. 중복 검사 등 존재 확인 

Map<String, User> emailUserMap = new HashMap<>();

if (emailUserMap.containsKey("test@email.com")) {
    // exists... 
        }

 

3. 데이터 캐싱 (예: DB 조회 결과 저장) 

DB에서 자주 조회되는 값을 매번 SQL로 가져오지 않고, HashMap에 저장해놓고 꺼내 쓰면 성능이 좋아진다.

 

// 예: 상품 ID를 키로, 상품 객체를 값으로 캐싱
Map<Long, Product> productCache = new HashMap<>();

public Product getProductById(Long id) {
    if (productCache.containsKey(id)) {
        return productCache.get(id); // 캐시 hit
    }
    Product product = productRepository.findById(id); // DB hit
    productCache.put(id, product);
    return product;
}

 

DB에서 자주 조회되는 값들은 read-heavy & low-change한 데이터인 경우가 많아 캐싱 대상이 된다.