Join Two List In Java & Remove Duplicates

Join Two List In Java & Remove Duplicates explains about how to merge two lists into a single list and removing duplicate entries using java api.

We have some situation where we need to join two or more Lists (ArrayList, LinkedList etc) into a single List.

There are lot of different ways, we can do this

In this post, we show 2 different examples to join two lists in Java.

1) List.addAll() method of java.util.Collection class
2) Apache Common ListUtils.union()
3) Join two List & Remove Duplicates

Required Libraries

You need to download

  1. Apache Commons Collections 3.2

1) List.addAll() method of java.util.Collection

By using List.addAll() method of java.util.Collection class, we can preserve the order of the objects inside the list


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

public class MergeTwoLists {
 
   public static void main(String[] args) {

     
ArrayList<String> list1 = new ArrayList<String>();
      list1.add
("Java");
      list1.add
("JSP");
      list1.add
("Servlet");
     
      ArrayList<String> list2 =
new ArrayList<String>();
      list2.add
("Spring");
      list2.add
("Hibernate");

      List<String> list3 =
new ArrayList<String>();
      list3.addAll
(list1);
      list3.addAll
(list2);
     
      System.out.println
("List1 " + list1);
      System.out.println
("List2 " + list2);
      System.out.println
("List3 " + list3);
     
  
}

}
output
List1 [Java, JSP, Servlet]
List2 [Spring, Hibernate]
List3 [Java, JSP, Servlet, Spring, Hibernate]

2) Apache Common ListUtils.union()

By using ListUtils.union() method, we can also get a combined list in java, it will also preserve the order of the objects inside the list

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections.ListUtils;

public class MergeTwoLists {

   public static void main(String[] args) {

     
ArrayList<String> list1 = new ArrayList<String>();
      list1.add
("Java");
      list1.add
("JSP");
      list1.add
("Servlet");
     
      ArrayList<String> list2 =
new ArrayList<String>();
      list2.add
("Spring");
      list2.add
("Hibernate");

      List<String> list3 =
new ArrayList<String>();
     
// ListUtils of Apache commons Collection
     
list3 = ListUtils.union(list1, list2);
     
      System.out.println
("List1 " + list1);
      System.out.println
("List2 " + list2);
      System.out.println
("Merged List Using Apache Commons Collections " + list3);
     
  
}

}
output
List1 [Java, JSP, Servlet]
List2 [Spring, Hibernate]
List3 [Java, JSP, Servlet, Spring, Hibernate]

1 2 Next





Your email address will not be published. Required fields are marked *