Java Program to Join Two Lists

In this program, you’ll learn different techniques to join two lists in Java.

Example 1: Join Two Lists using addAll()

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. public class JoinLists {
  4. public static void main(String[] args) {
  5. List<String> list1 = new ArrayList<String>();
  6. list1.add("a");
  7. List<String> list2 = new ArrayList<String>();
  8. list2.add("b");
  9. List<String> joined = new ArrayList<String>();
  10. joined.addAll(list1);
  11. joined.addAll(list2);
  12. System.out.println("list1: " + list1);
  13. System.out.println("list2: " + list2);
  14. System.out.println("joined: " + joined);
  15. }
  16. }

When you run the program, the output will be:

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

In the above program, we used List‘s addAll() method to join lists list1 and list2 to the joined list.


Example 2: Join Two Lists using union()

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import org.apache.commons.collections.ListUtils;
  4. public class JoinLists {
  5. public static void main(String[] args) {
  6. List<String> list1 = new ArrayList<String>();
  7. list1.add("a");
  8. List<String> list2 = new ArrayList<String>();
  9. list2.add("b");
  10. List<String> joined = ListUtils.union(list1, list2);
  11. System.out.println("list1: " + list1);
  12. System.out.println("list2: " + list2);
  13. System.out.println("joined: " + joined);
  14. }
  15. }

The output of this program is the same.

In the above program, we used union() method to join the given lists to joined.


Example 3: Join Two Lists using stream

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.stream.Collectors;
  4. import java.util.stream.Stream;
  5. public class JoinLists {
  6. public static void main(String[] args) {
  7. List<String> list1 = new ArrayList<String>();
  8. list1.add("a");
  9. List<String> list2 = new ArrayList<String>();
  10. list2.add("b");
  11. List<String> joined = Stream.concat(list1.stream(), list2.stream())
  12. .collect(Collectors.toList());
  13. System.out.println("list1: " + list1);
  14. System.out.println("list2: " + list2);
  15. System.out.println("joined: " + joined);
  16. }
  17. }

The output of this program is the same.

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