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

Java에서 두 개의 리스트(List)를 하나로 병합하는 방법


리스트(List)란 무엇인가?

이 글에서는 Java에서 두 개의 리스트를 하나로 병합하는 방법을 단계별로 알아보겠습니다. 먼저 리스트에 대해 간단히 짚고 넘어갈 텐데요, 리스트는 요소들을 순서대로 저장하고 접근할 수 있는 정렬된 컬렉션(Collection)입니다. 인덱스 기반의 메서드를 제공하여 요소의 삽입, 수정, 삭제, 검색이 자유롭고, 중복 요소 역시 허용됩니다.

병합 결과 미리 보기

아래는 두 리스트를 병합했을 때의 동작 예시입니다.

입력값

첫 번째 리스트: [45, 60, 95]
두 번째 리스트: [105, 120]

기대 출력값

두 리스트를 병합한 결과: [45, 60, 95, 105, 120]

알고리즘

두 리스트를 병합하는 핵심은 addAll() 메서드입니다. 전체 과정은 다음과 같습니다.

1단계 - 시작
2단계 - input_list_1, input_list_2, result_list라는 세 개의 정수형(Integer) 리스트를 선언한다.
3단계 - 각 리스트에 값을 정의(추가)한다.
4단계 - result_list.addAll(input_list_1)을 호출하여 첫 번째 리스트의 모든 요소를 결과 리스트에 추가한다.
5단계 - result_list.addAll(input_list_2)를 호출하여 두 번째 리스트의 모든 요소를 결과 리스트에 추가한다.
6단계 - result_list를 화면에 출력한다.
7단계 - 종료

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

이 예제에서는 모든 연산을 하나의 main 메서드 안에 함께 작성합니다. 코드가 짧고 전체 흐름을 한눈에 파악하기 좋다는 장점이 있습니다.

import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      List<Integer> input_list_1 = new ArrayList<>();
      input_list_1.add(45);
      input_list_1.add(60);
      input_list_1.add(95);
      System.out.println("The first list is defined as: " + input_list_1);
      List<Integer> input_list_2 = new ArrayList<>();
      input_list_2.add(105);
      input_list_2.add(120);
      System.out.println("The second list is defined as: " + input_list_2);
      List<Integer> result_list = new ArrayList<>();
      result_list.addAll(input_list_1);
      result_list.addAll(input_list_2);
      System.out.println(" The list after merging the two lists: " + result_list);
   }
}

출력 결과

The first list is defined as: [45, 60, 95]
The second list is defined as: [105, 120]

The list after merging the two lists: [45, 60, 95, 105, 120]

예제 2: 객체 지향 방식으로 병합 로직 분리하기

이 예제에서는 병합 연산을 별도의 메서드로 캡슐화하여 객체 지향 프로그래밍(OOP) 스타일로 구현합니다. 병합 로직을 재사용할 수 있어 코드 관리가 훨씬 수월해집니다.

import java.util.ArrayList;
import java.util.List;
public class Demo {
   static void merge(List<Integer> input_list_1, List<Integer> input_list_2){
      List<Integer> result_list = new ArrayList<>();
      result_list.addAll(input_list_1);
      result_list.addAll(input_list_2);
      System.out.println("\nThe list after merging the two lists: " + result_list);
   }
   public static void main(String[] args) {
      List<Integer> input_list_1 = new ArrayList<>();
      input_list_1.add(45);
      input_list_1.add(60);
      input_list_1.add(95);
      System.out.println("The first list is defined as: " + input_list_1);
      List<Integer> input_list_2 = new ArrayList<>();
      input_list_2.add(105);
      input_list_2.add(120);
      System.out.println("The second list is defined as: " + input_list_2);
      merge(input_list_1, input_list_2);
   }
}

출력 결과

The first list is defined as: [45, 60, 95]
The second list is defined as: [105, 120]

The list after merging the two lists: [45, 60, 95, 105, 120]

참고: Java 8 스트림(Stream)으로 병합하기

Java 8 이상을 사용한다면 Stream.concat()을 활용해 더욱 간결하게 두 리스트를 병합할 수도 있습니다.

import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;
import java.util.stream.Stream;

List<Integer> result_list = Stream.concat(
   input_list_1.stream(), input_list_2.stream())
   .collect(Collectors.toList());
System.out.println(result_list); // [45, 60, 95, 105, 120]

마무리

지금까지 addAll() 메서드를 활용해 두 개의 리스트를 병합하는 두 가지 방식, 즉 main 메서드에서 직접 처리하는 방법과 별도의 메서드로 분리하는 객체 지향적 방법을 살펴보았습니다. 규모가 작은 코드라면 예제 1처럼 간단하게 작성해도 충분하지만, 재사용성과 유지보수를 고려한다면 예제 2처럼 로직을 메서드로 분리하는 것이 좋습니다.