Join Two Lists in Java

Exercise:

Write a Java Program to join two lists.

1.join using addAll()

Click Here to View the Solution!
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("Hello");
         List<String> list2 = new ArrayList<String>();
         list2.add("World");
  
         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);
  
     }
 } 
Click Here to View the Output!
 list1: [Hello]
 list2: [World]
 joined: [Hello, World]
Click Here to View the Explanation!

In this program, a built-in List method called addAll() is utilized to append one list after the other in a separate list called joined. This way both these lists list1 and list2 are joined.

2.Join using stream

Click Here to View the Solution!
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("Hello");
        List<String> list2 = new ArrayList<String>();
        list2.add("World");
 
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);
     }
} 
Click Here to View the Output!
 list1: [Hello]
 list2: [World]
 joined: [Hello, World]
Click Here to View the Explanation!

In this program, a stream method called concat() first converts both the lists list1 and list2 into streams and then joins them. Then the resultant stream is converted back into a list using the toList() method and stored in the joined variable.

%d bloggers like this: