📕🐘 도로락 - 코끼리를 냉장고에 넣는 방법
자바[Java] | 2017. 11. 30. 23:43

[JAVA] Collection List, Map 합치는 방법

서로 다른 List, Map 병합 방법

List와 Map 등 여러 개의 서로 다른 객체를 하나의 List 또는 Map으로 병합해야 할 때가 있습니다.

Map 을 병합할 때는 다음과 같이 putAll()을 사용하면 됩니다. 사실 putAll은 여러 개의 key value를 동시에 추가하는 개념이지만 결국 두 개의 Map을 병합한다는 의미가 있습니다.

import java.util.HashMap;
import java.util.Map;

public class CollectionMerge {
    public static void main(String[] args) {
        Map<String, String> map1 = new HashMap<String, String>();
        map1.put("a", "a");
        map1.put("b", "b");
        map1.put("c", "c");

        Map<String, String> map2 = new HashMap<String, String>();
        map2.put("d", "d");
        map2.put("e", "e");
        map2.put("f", "f");

        map1.putAll(map2); //맵에 추가

        System.out.println(map1); //{a=a, b=b, c=c, d=d, e=e, f=f}
    }
}

만약 서로 다른 제네릭 타입의 Map을 병합하려 하면 다음과 같이 예외가 발생하니 주의하도록 합니다.

Map<String, String> map1 = new HashMap<String, String>();
Map<String, Integer> map2 = new HashMap<String, Integer>();
map1.putAll(map2); //맵에 추가
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    The method putAll(Map<? extends String,? extends String>) in the type Map<String,String> is not applicable for the arguments (Map<String,Integer>)
    at snippet.CollectionMerge.main(CollectionMerge.java:19)

List 를 병합하는 방법도 마찬가지입니다. List의 경우는 addAll()을 사용하면 됩니다.

import java.util.ArrayList;
import java.util.List;

public class CollectionMerge {
    public static void main(String[] args) {
        List<String> list1 = new ArrayList<String>();
        list1.add("a");
        list1.add("b");
        list1.add("c");

        List<String> list2 = new ArrayList<String>();
        list2.add("d");
        list2.add("e");
        list2.add("f");

        list1.addAll(list2);

        System.out.println(list1); //[a, b, c, d, e, f]
    }
}
도로락

도로락

Writer

IT, 프로그래밍, 컴퓨터 활용 정보 등을 위한 블로그