How to concatenate 2 List in Java

 

We have seen situation that we need to merge or concatenate 2 Lists of same type into single List. To do this instead of iterating all elements and adding to new List we can use addAll() function to concatenate 2 List items. There are two types of addAll() function in Java.
How to concatenate 2 List in Java
  • First we can merge all elements at the end of List.
  • Second we can insert all of the elements from specified position of List.
Lets see both types by simple example


import java.util.ArrayList;
import java.util.List;

public class ListTest {

 public static void main(String[] args) {
  
  List<String> list1 = new ArrayList<String>();
  list1.add("one");
  list1.add("two");
  list1.add("three");
  
  List<String> list2 = new ArrayList<String>();
  list2.add("four");
  list2.add("five");
  list2.add("six");
  
  // First type merging at the end of list
  list1.addAll(list2);
 
  System.out.println("First Type : "+list1);
  
  list1.clear();
  list1.add("one");
  list1.add("two");
  list1.add("three");
  
  // Second type merging at index(1)
  list1.addAll(1, list2);
  
  System.out.println("\nSecond Type : "+list1);
 }
}

OUTPUT:


First Type : [one, two, three, four, five, six]

Second Type : [one, four, five, six, two, three]

No comments:
Write comments