English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List (List)

Java Queue (queue)

Java Map collection

Java Set collection

Java Input/Output (I/O)

Java Reader/Writer

Java other topics

Java program to merge two lists

Java Comprehensive Examples

In this program, you will learn various techniques to merge two lists in Java.

Example1:Merge two lists using addAll()

import java.util.ArrayList;
import java.util.List;
public class JoinLists {}}
    public static void main(String[] args) {
        List<String> list1 = new ArrayList<String>();
        list1.add("a");
        List<String> list2 = new ArrayList<String>();
        list2.add("b");
        List<String> joined = new ArrayList<String>();
        joined.addAll(list1);
        joined.addAll(list2);
        System.out.println("list1: " + list1);
        System.out.println("list2: " + list2);
        System.out.println("joined: " + joined);
    }
}

When running the program, the output is:

list1: [a]
list2: [b]
joined: [a, b]

In the above program, we use the List's addAll() method to merge the list list1and list2List.

Example2:Merge two lists using union()

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections.ListUtils;
public class JoinLists {}}
    public static void main(String[] args) {
        List<String> list1 = new ArrayList<String>();
        list1.add("a");
        List<String> list2 = new ArrayList<String>();
        list2.add("b");
        List<String> joined = ListUtils.union(list1, list2);
        System.out.println("list1: " + list1);
        System.out.println("list2: " + list2);
        System.out.println("joined: " + joined);
    }
}

The output of the program is the same.

In the above program, we use the union() method to merge the given list into joined.

Example3:Merge two lists using streams

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class JoinLists {}}
    public static void main(String[] args) {
        List<String> list1 = new ArrayList<String>();
        list1.add("a");
        List<String> list2 = new ArrayList<String>();
        list2.add("b");
        List<String> joined = Stream.concat(list1.stream(), list2.stream())
                .collect(Collectors.toList()));
        System.out.println("list1: " + list1);
        System.out.println("list2: " + list2);
        System.out.println("joined: " + joined);
    }
}

The output of the program is the same.

In the above program, we use the Stream's concat() method to concatenate two lists converted to streams. Then, we convert them back to List using toList().

Java Comprehensive Examples