Java 程式來合併兩個列表


在本文中,我們將瞭解如何合併兩個列表。列表是一個有序集合,它允許我們按順序儲存和訪問元素。它包含用於插入、更新、刪除和搜尋元素的基於索引的方法。它還可以包含重複元素。

以下是相同的演示 −

假設我們的輸入是

First list: [45, 60, 95]
Second list: [105, 120]

期望的輸出將是

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

演算法

Step 1 - START
Step 2 - Declare three integer lists namely input_list_1, input_list_2 and result_list.
Step 3 - Define the values.
Step 4 - Use result_list.addAll(input_list_1) to add all the elements of the input_list_1 to the result list.
Step 5 - Use result_list.addAll(input_list_2) to add all the elements of the input_list_2 to the result list.
Step 6 - Display the result_list.
Step 7 - Stop

示例 1

在這裡,我們把所有操作繫結在一起,放在“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("\nThe 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

在這裡,我們將操作封裝成函式,展示面向物件程式設計。

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]

更新於: 30-Mar-2022

394 次瀏覽

啟動你的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.