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.