Home
Data Structure
HashMap에서 하나의 키에 다중 값을 넣고 싶을 때
devfoxstar
devfoxstar
February 02, 2022
1 min

HashMap은 Map 인터페이스를 구현한 Map 컬렉션입니다. Key-Value 쌍으로 저장되며, 자주 사용하는 자료 구조 중에 하나입니다.

데이터를 저장할 때, Key에는 중복 값이 들어갈 수 없습니다. 만약 Key에 중복 값이 들어오면, 기존 Key에 맵핑된 Value는 새로운 값으로 대체됩니다.

그럼 하나의 키에 다중 값을 넣고 싶으면 어떻게 해야 할까요? 값을 배열로 선언하면 됩니다.

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

이제 하나의 키에 여러 개의 값을 담을 수 있습니다. 간단히 예제를 보겠습니다.

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

for (int i = 0; i < 5; i++) {
    ArrayList<Integer> list = new ArrayList<Integer>();
    for (int j = 0; j < 5; j++) {
        list.add(i + j);
    }
    map.put(i, list);
}

HashMap에 담긴 결과 값은 아래와 같습니다.

{0=[0, 1, 2, 3, 4], 1=[1, 2, 3, 4, 5], 2=[2, 3, 4, 5, 6], 3=[3, 4, 5, 6, 7], 4=[4, 5, 6, 7, 8]}

Tags

#DataStructure#자료구조#HashMap

Related Posts

자료구조 - 리스트 (ArrayList, LinkedList, Vector)
March 09, 2022
1 min
© 2024, All Rights Reserved.

Quick Links

About Me

Media