java 合并两个列表

Merging two lists in Java is often a useful operation. These lists can be ArrayLists or LinkedLists.

合并Java中的两个列表通常是有用的操作。 这些列表可以是ArrayLists或LinkedLists。

如何在Java中合并两个列表 (How to Merge Two Lists in Java)

There are multiple ways we can merge two lists in Java. Let’s explore some of the straightforward ones to get your job done!

我们可以通过多种方式合并Java中的两个列表。 让我们探索一些简单的方法来完成您的工作!

1. addAll()方法合并两个列表 (1. The addAll() method to merge two lists)

The addAll() method is the simplest and most common way to merge two lists.

addAll()方法是合并两个列表的最简单,最常见的方法。

For ArrayList :

对于ArrayList:


import java.util.ArrayList;public class Main {public static void main(String[] args){
ArrayList<Integer> l1 = new ArrayList<Integer>();l1.add(1);l1.add(3);l1.add(5);
ArrayList<Integer> l2 = new ArrayList<Integer>();l2.add(2);l2.add(4);l2.add(6);
ArrayList<Integer> merge = new ArrayList<Integer>();merge.addAll(l1);merge.addAll(l2);
System.out.println("L1 : "+l1);
System.out.println("L2 : "+l2);
System.out.println("Merged : "+merge);
}
}
Output
输出量

Note the order of appearance of elements matches the order in which addAll() is called.

请注意,元素的出现顺序与调用addAll()的顺序匹配。

For LinkedLists:

对于LinkedList:


import java.util.LinkedList;public class Main {public static void main(String[] args){
LinkedList<Integer> L1 = new LinkedList<>();L1.add(1);L1.add(3);L1.add(5);
LinkedList<Integer> L2 = new LinkedList<>();L2.add(2);L2.add(4);L2.add(6);
LinkedList<Integer> merged = new LinkedList<>();merged.addAll(L1);merged.addAll(L2);System.out.println("L1 : "+L1);
System.out.println("L2 : "+L2);
System.out.println("Merged : "+merged);
}
}
Output
输出量

2.使用迭代器合并Java中的两个列表 (2. Using iterators to merge two lists in Java)

We can use an Iterator to traverse the list and merge.

我们可以使用Iterator遍历列表并合并。

For ArrayList :

对于ArrayList:


import java.util.ArrayList;public class Main {public static void main(String[] args){
ArrayList<Integer> l1 = new ArrayList<Integer>();l1.add(1);l1.add(3);l1.add(5);
ArrayList<Integer> l2 = new ArrayList<Integer>();l2.add(2);l2.add(4);l2.add(6);ArrayList<Integer> Itmerge = new ArrayList<>();Iterator i = l1.iterator();while (i.hasNext()) {Itmerge.add((int)i.next());}i=l2.iterator();while (i.hasNext()) {Itmerge.add((int)i.next());}
System.out.println("L1 : "+l1);
System.out.println("L2 : "+l2);
System.out.println("Merged : "+Itmerge);
}
}

Iterator first traverses the ArrayList l1 and adds all the elements to Itmerge, it then traverses the ArrayList l2 and adds all the elements to Itmerge.

迭代器首先遍历ArrayList l1并将所有元素添加到Itmerge,然后遍历ArrayList l2并将所有元素添加到Itmerge。

Output
输出量

Another way to merge the two lists is to simply add elements from one list to the other. There is no need to create a new list unless you need to keep the existing data intact.

合并两个列表的另一种方法是简单地将一个列表中的元素添加到另一个列表中。 除非您需要保持现有数据不变,否则无需创建新列表。


Iterator i = l1.iterator();
while (i.hasNext())
{l2.add((int)i.next());
}System.out.println("Merged : "+l2);

In this case, all the elements are added to the list l2. This saves the memory spent in the creation of an extra list. Adding the elements of one list to another saves the extra traversal.

在这种情况下,所有元素都添加到列表l2中。 这样可以节省创建额外列表所花费的内存。 将一个列表的元素添加到另一个列表可以节省额外的遍历。

Output
输出量

For LinkedList:

对于LinkedList:


import java.util.LinkedList;public class Main {public static void main(String[] args){
LinkedList<Integer> L1 = new LinkedList<>();L1.add(1);L1.add(3);L1.add(5);
LinkedList<Integer> L2 = new LinkedList<>();L2.add(2);L2.add(4);L2.add(6);
LinkedList<Integer> merged = new LinkedList<>();Iterator i = L1.iterator();while (i.hasNext()) {L2.add((int)i.next());}
System.out.println(L2);
}
}

3.使用for循环合并多个列表 (3. Merge Multiple Lists using for loop)

For loop is also useful to merge two lists.

For循环对于合并两个列表也很有用。

For ArrayList:

对于ArrayList:


import java.util.ArrayList;public class Main {public static void main(String[] args){
ArrayList<Integer> l1 = new ArrayList<Integer>();l1.add(1);l1.add(3);l1.add(5);
ArrayList<Integer> l2 = new ArrayList<Integer>();l2.add(2);l2.add(4);l2.add(6);
ArrayList<Integer> Itmerge = new ArrayList<>();for(int i=0;i<l1.size();i++){Itmerge.add(l1.get(i));}for(int i=0;i<l2.size();i++){Itmerge.add(l2.get(i));}
System.out.println(Itmerge);
}
}

The loop traverses both the ArrayLists and adds each element one by one to a newly created list.

该循环遍历两个ArrayList,并将每个元素一个一个地添加到新创建的列表中。

Adding the elements of one list to another saves the extra traversal.

将一个列表的元素添加到另一个列表可以节省额外的遍历。

for(int i=0;i<l2.size();i++){l1.add(l2.get(i));}
System.out.println(l1);

This for loop adds the elements of l2 to l1 one by one. In this case, l1 will contain the final list of merged elements.

此for循环将l2的元素一一添加到l1。 在这种情况下,l1将包含合并元素的最终列表。

Output
输出量

For LinkedList:

对于LinkedList:

To understand the traversal of linked lists a little better let us define our own linked list.

为了更好地理解链表的遍历,让我们定义自己的链表。

This will require a class for nodes. A node needs two things, data and the address of the next node.

这将需要一个节点类。 一个节点需要两件事,数据和下一个节点的地址。

Code for class node :

类节点的代码:


public class node {int data;node next;public node(int data){this.data=data;next=null;}
}

Note that the next is of type node since it stores the address of a node. Creating the same two lists as used in earlier examples:

注意下一个是节点类型,因为它存储节点的地址。 创建与先前示例相同的两个列表:


public class Main {public static void main(String[] args){        node head = new node(1);node temp = new node(3);head.next=temp;node temp1 = new node(5);temp.next=temp1;node head2 = new node(2);node temp2 = new node(4);head2.next=temp2;node temp3 = new node(6);temp2.next=temp3;
}
}

This will create lists that look like :

这将创建如下列表:

Each arrow represents the next link. To link the two lists together we need to link the end of one list to the head of the second.

每个箭头代表下一个链接。 要将两个列表链接在一起,我们需要将一个列表的末尾链接到第二个列表的头。

This can be done as follows:

可以按以下步骤完成:


node trav=head;
while(trav.next!=null){trav=trav.next;
}
trav.next=head2;

A node ‘trav’ is initiated and pointed at the head of the first list. The first list is traversed until trav reaches the end of the first list.

节点“ trav”被启动并指向第一个列表的开头。 遍历第一个列表,直到trav到达第一个列表的末尾。

When the end is reached, it changes the next link of the last node to head of the second list. This forms a link between the two lists.

到达末尾时,它将最后一个节点的下一个链接更改为第二个列表的开头。 这形成了两个列表之间的链接。

Printing all the lists:

打印所有列表:


public class Main {public static void main(String[] args){ node head = new node(1);node temp = new node(3);head.next=temp;node temp1 = new node(5);temp.next=temp1;node head2 = new node(2);node temp2 = new node(4);head2.next=temp2;node temp3 = new node(6);temp2.next=temp3;//printing list 1System.out.println("List 1 :");node trav = head;while(trav!=null){System.out.print(trav.data + " ");trav=trav.next;}System.out.println();
//prinitng list 2System.out.println("List 2 :");trav= head2;while(trav!=null){System.out.print(trav.data + " ");trav=trav.next;}System.out.println();//merging the two listtrav=head;while(trav.next!=null){trav=trav.next;}trav.next=head2;
// printing merged listSystem.out.println("merged list :");trav = head;while(trav!=null){System.out.print(trav.data + " ");trav=trav.next;}
}
}
Output
输出量

结论 (Conclusion )

We saw the different ways to merge two lists in Java. These are ranged from inbuilt functions to basic for loops. The last example above gives a deeper understanding of how lists work in Java. Using the approach of the last example you can have more control over the order in which elements appear in the list.

我们看到了在Java中合并两个列表的不同方法。 这些范围从内置函数到基本的for循环。 上面的最后一个示例更深入地了解了列表在Java中的工作方式。 使用最后一个示例的方法,您可以更好地控制元素在列表中出现的顺序。

翻译自: https://www.journaldev.com/41681/merge-two-lists-in-java

java 合并两个列表

java 合并两个列表_如何在Java中合并两个列表?相关推荐

  1. python生成指定长度的列表_如何在python中创建固定大小列表?

    (tl;博士:您问题的确切答案是numpy.empty_like或x = list(size=10000),但您可能不在乎,可以使用myList = [None]*10000逃脱.) 简单的方法 您可 ...

  2. python创建长度为20的列表_如何在python中创建固定大小列表?

    小编典典 (tl;博士:您问题的确切答案是numpy.empty或numpy.empty_like,但您可能不在乎,可以摆脱使用的困扰myList = [None]*10000.) 简单的方法 您可以 ...

  3. python一行输出多个数据_如何在Python中让两个print()函数的输出打印在一行内?

    1.两个连续的print()函数为什么在输出时内容会分行显示? 解:print()中有两个默认参数sep和end,其中sep是代替分隔符,end是代替末尾的换行符,默认使用','代替空格,且默认末尾加 ...

  4. python 两个列表比较_如何在Python中比较两个列表

    python 两个列表比较 In this article, we will understand the different ways to compare two lists in Python. ...

  5. arcgis两张图层不能同时显示_如何在ArcGIS中合并两个“不兼容”的多边形图层?...

    "我已经尝试过'积分'了.它在消除间隙方面起作用,但还可以根据指定的簇公差将所有多边形进行概括." 问题是您是否要保持"灰色"多边形的分离状态.为了不泛化边界, ...

  6. java 查找链表中间元素_如何在Java中一次性查找Java中链表的中间元素

    如何在一次传递中找到LinkedList的中间元素?这是一个 Java 和非Java程序员面试时经常被问到的编程问题.这个问题类似于检查回文或计算阶乘,有时也会要求编写代码.为了回答这个问题,候选人必 ...

  7. java字符串字符排列组合_如何在Java中查找字符串的所有排列

    java字符串字符排列组合 In this tutorial, we will learn how to find the permutation of a String in a Java Prog ...

  8. python定义一个列表_如何在Python中创建用户定义的列表?

    你需要将怪物的数量发送给使用它的函数:def welcome(): number = monsters() print('Alright, ' + str(number) + ' monsters.' ...

  9. append 后如何删除_如何在STATA中合并数据文件呢?

    ❝ 作者:江小白 邮箱:jieresearch@163.com ❞ 我们在使用stata进行数据分析时,可能涉及多个数据文档的合并操作或者同时使用不同数据集中的多个变量,这都需要我们进行文档间不同变量 ...

最新文章

  1. 转载:thread的六种状态
  2. linux send与recv函数详解
  3. (JAVA学习笔记) 接口
  4. evans pde 第三章_智慧树报关实务第三章答案
  5. Android应用开发基础篇(1)-----Button
  6. Matlab代码提示“svmtrain已删除 请改用fitcsvm”,以及svmpredict没有返回结果label和精度accuracy的解决办法
  7. 搭建大数据开发环境-Hadoop篇
  8. 细腻剖析2010年3月四级网络工程师试卷解题思路
  9. 2.[精通Hibernate笔记]整合Spring
  10. 学前端有什么好方法,怎么才能更快学会前端?
  11. C#数字日期转成中文日期
  12. 在redis上实现分布式锁
  13. 你最喜欢哪款游戏的界面风格,为什么?
  14. SQL 常用语句INSERT INTO,UPDATE,DELETE
  15. 百兆和千兆直通线与交叉线的制作方法
  16. 【Python】 调用百度地图API抓取西安市小区信息
  17. 如何防止form表单重复提交
  18. kata cantainer介绍及Ubuntu安装kata cantainer
  19. mysql dump 10.13 下载_mysqldump.exe 文件下载
  20. 云米递交招股书:上半年净利7029万 雷军系持股40%

热门文章

  1. [转载] python实现一个简易的计算器
  2. 1.PHP与Web页面的交互
  3. svn源代码变动后一分钟内启动执行?按照定好的时间点执行?(项目构建的触发)...
  4. AndroidStudio 内存泄漏分析 Memory Monitor
  5. mysql开启远程可连接
  6. loadrunner提高篇 - 关联技术的经典使用
  7. yolo之---非极大值抑制
  8. pytorch---之item()
  9. php网页示例,新手入门:初学动态网页PHP的18个例子
  10. java linux ping ip,java linux ping命令