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]