Join Two Array In Java & Remove Duplicates

Join Two Array In Java & Remove Duplicates explains about how to join two Array into a single Array and removing duplicate entries using java api.

We have some situation where we need to join two or more Array into a single Array.

There are lot of different ways, we can do this

In this post, we show 3 different examples to join two Array in Java.

1) List.addAll() & List.toArray() method of java.util.Collection class
2) Apache Common ArrayUtils.addAll(first, second)
3) Join two Array & Remove Duplicates

Required Libraries

You need to download

  1. Apache Commons Collections 3.2

1) List.addAll() & List.toArray() 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, after processing, we need to convert the list into array using List.toArray() method

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

public class MergeTwoArray {

/**
    *
Merge Two Array Using List.addAll()
    */
  
public static void main(String[] args) {

     
String array1[] = { "Java", "JSP", "Servlet" };
      String array2
[] = { "Spring", "Hibernate" };
     
      List<String> list3 =
new ArrayList<String>();
      list3.addAll
(Arrays.asList(array1));
      list3.addAll
(Arrays.asList(array2));
      String array3
[] = list3.toArray(new String[list3.size()]);
     
      System.out.println
("Array1 " + Arrays.toString(array1));
      System.out.println
("Array2 " + Arrays.toString(array2));
      System.out.println
("Array3 " + Arrays.toString(array3));
    
  
}

}
output
Array1 [Java, JSP, Servlet]
Array2 [Spring, Hibernate]
Array3 [Java, JSP, Servlet, Spring, Hibernate]

2) Apache Common ArrayUtils.addAll()

By using ArrayUtils.addAll() method, we can also get a combined Array in java, it will also preserve the order of the objects inside the array

import java.util.Arrays;
import org.apache.commons.collections.ArrayUtils;

public class MergeTwoArray {

/**
    *
Merge Two Array Using Apache Commons ArrayUtils.addAll()
    */
  
public static void main(String[] args) {

     
String array1[] = { "Java", "JSP", "Servlet" };
      String array2
[] = { "Spring", "Hibernate" };
     
      String array3
[] = ArrayUtils.addAll(array1, array2);
     
      System.out.println
("Array1 " + Arrays.toString(array1));
      System.out.println
("Array2 " + Arrays.toString(array2));
      System.out.println
("Array3 " + Arrays.toString(array3));
    
  
}

}
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 *