How to join two Lists in Java
By:Roy.LiuLast updated:2019-08-18
In this article, we show you 2 examples to join two lists in Java.
- JDK – List.addAll()
- Apache Common – ListUtils.union()
1. List.addAll() example
Just combine two lists with List.addAll().
JoinListsExample.java
package com.mkyong.example;
import java.util.ArrayList;
import java.util.List;
public class JoinListsExample {
public static void main(String[] args) {
List<String> listA = new ArrayList<String>();
listA.add("A");
List<String> listB = new ArrayList<String>();
listB.add("B");
List<String> listFinal = new ArrayList<String>();
listFinal.addAll(listA);
listFinal.addAll(listB);
//same result
//List<String> listFinal = new ArrayList<String>(listA);
//listFinal.addAll(listB);
System.out.println("listA : " + listA);
System.out.println("listB : " + listB);
System.out.println("listFinal : " + listFinal);
Output
listA : [A] listB : [B] listFinal : [A, B]
Append Lists
To append ListB to the end of ListA, uses
To append ListB to the end of ListA, uses
listA.addAll(listB);
2. ListUtils.union example
Apache common library – ListUtils.union().
JoinListsExample2.java
package com.mkyong.example;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections.ListUtils;
public class JoinListsExample2 {
public static void main(String[] args) {
List<String> listA = new ArrayList<String>();
listA.add("A");
List<String> listB = new ArrayList<String>();
listB.add("B");
List<String> listFinal = ListUtils.union(listA, listB);
System.out.println("listA : " + listA);
System.out.println("listB : " + listB);
System.out.println("listFinal : " + listFinal);
Output
listA : [A] listB : [B] listFinal : [A, B]
Dig into the source code, the ListUtils.union is using the same List.addAll() to combine lists.
ListUtils.java
public static List union(final List list1, final List list2) {
final ArrayList result = new ArrayList(list1);
result.addAll(list2);
return result;
References
From:一号门
Previous:Spring MVC and List Example

COMMENTS