Java/컬렉션

[Java]두 개의 ArrayList 합치기(merge)

DevStory 2022. 5. 30.

이번 포스팅은 두 개의 ArrayList를 하나의 ArrayList로 합치는 방법을 소개합니다.


List.addAll()

addAll() 메서드는 인자로 전달된 컬렉션 객체의 모든 요소를 ArrayList 끝에 추가합니다. 다음 예제는 liOne 끝에 liTwo의 모든 요소를 추가합니다.

ArrayList<String> liOne = new ArrayList<>();
liOne.add("A");
liOne.add("B");
liOne.add("C");

ArrayList<String> liTwo = new ArrayList<>();
liTwo.add("D");
liTwo.add("E");
liTwo.add("F");

System.out.println("addAll() 메서드 호출 전");
System.out.println(liOne);

liOne.addAll(liTwo);

System.out.println("addAll() 메서드 호출 후");
System.out.println(liOne);

실행 결과

addAll() 메서드 호출 전
[A, B, C]
addAll() 메서드 호출 후
[A, B, C, D, E, F]

Stream.flatMap()

Java 8에 도입된 Stream API를 사용하여 두 개의 ArrayList를 하나로 합칠 수 있습니다. Stream의 flatMap() 메서드는 단일 스트림에서 두 개 이상의 컬렉션 요소를 가져온 다음 단일 스트림을 반환합니다.

 

flatMap() 메서드에서 반환된 단일 스트림을 컬렉션으로 변환함으로써 두 개의 ArrayList를 하나로 합칠 수 있습니다.

 

다음 예제는 Stream API의 flatMap() 메서드를 사용하여 두 개의 ArrayList를 하나의 ArrayList로 병합합니다.

ArrayList<String> liOne = new ArrayList<>();
liOne.add("A");
liOne.add("B");
liOne.add("C");

ArrayList<String> liTwo = new ArrayList<>();
liTwo.add("D");
liTwo.add("E");
liTwo.add("F");

List<String> mergedList = Stream.of(liOne, liTwo)
                        .flatMap(Collection::stream)
                        .collect(Collectors.toList());

System.out.println("Stream API 호출 후");
System.out.println(mergedList);

실행 결과

Stream API 호출 후
[A, B, C, D, E, F]

Stream의 flatMap() 메서드는 기존 ArrayList 객체를 변형하지 않고 새로운 컬렉션 객체를 생성합니다.


중복 제거

addAll() 메서드와 Stream의 flatMap() 메서드를 사용하는 방법은 중복 요소를 제거하지 않습니다. 두 개의 ArrayList 객체에서 중복되는 요소를 제거하고 싶은 경우 다음 두 가지 방법을 사용할 수 있습니다.

 

첫 번째 방법은 LinkedHashSet를 사용합니다. Set은 고유한 요소만 허용하므로 중복된 요소가 존재하지 않습니다.

두 번째 방법은 removeAll() 메서드로 중복 요소를 제거 후 addAll() 메서드를 사용합니다.

 

다음 예제는 LinkedHashSet을 사용하는 방법입니다.

ArrayList<String> liOne = new ArrayList<>();
liOne.add("A");
liOne.add("B");
liOne.add("C");

ArrayList<String> liTwo = new ArrayList<>();
liTwo.add("B");
liTwo.add("C");
liTwo.add("D");
liTwo.add("E");
liTwo.add("F");

Set<String> set = new LinkedHashSet<>(liOne);
set.addAll(liTwo);
List<String> mergedList = new ArrayList<>(set);

System.out.println("LinkedHashSet 사용");
System.out.println(mergedList);

실행 결과

LinkedHashSet 사용
[A, B, C, D, E, F]

 

다음 예제는 removeAll() 메서드로 중복 요소를 제거 후 addAll() 메서드를 호출합니다.

ArrayList<String> liOne = new ArrayList<>();
liOne.add("A");
liOne.add("B");
liOne.add("C");

ArrayList<String> liTwo = new ArrayList<>();
liTwo.add("B");
liTwo.add("C");
liTwo.add("D");
liTwo.add("E");
liTwo.add("F");

List<String> mergedList = new ArrayList<>(liOne);
mergedList.removeAll(liTwo);
mergedList.addAll(liTwo);

System.out.println("removeAll() 메서드와 addAll() 메서드 사용");
System.out.println(mergedList);

실행 결과

removeAll() 메서드와 addAll() 메서드 사용
[A, B, C, D, E, F]

정리

  • addAll() 메서드와 Stream의 flatMap() 메서드를 사용하여 두 개의 ArrayList를 합칠 수 있습니다.
  • 중복 요소를 제거하고 싶은 경우 LinkedHashSet 또는 중복 요소 제거 후 addAll() 메서드를 호출합니다.
반응형

댓글