Remove Element From Array in Java

How to remove an element from an array in Java by index or by value. There are different ways to remove an element from an array by index and to remove by the value first find the index of given element/value and then use the previous approach. Let us discuss them in detail.


Remove Element From Array by Index in Java

There are different ways to remove an element at a specific index from an array in Java.
a) Remove element using another array and Loop
b) Using System.arraycopy()
c) With help of Java 8 Streams
d) Using ArrayList

Remove Element using Another Array and Loop

It is the naive or basic approach to remove an element using another array and loops. The operations can be performed as,

a) Take an array and the index.
b) Create a new array with size 1 less than the original array.
c) Copy elements of the original array to the new array.
d) Skip the copying element at the index position.
e) Return the copied new array.

import java.util.Arrays;
public class ArrayTest {

   public static void main(String[] args) {
      // original array
      int arr[] = { 10, 20, 30, 40, 50 };

      // index of element to be removed 
      int index = 3;

      // display old array
      System.out.println("Original array: " + Arrays.toString(arr));

      // remove
      arr = removeElement(arr, index);

      // display new array
      System.out.println("New array: " + Arrays.toString(arr));
   }

   // method to remove element at specific index
   public static int[] removeElement(int[] arr, int index) {

      // if array is null or index is negative or more then size 
      // return original array
      if(arr == null || index < 0 || index >= arr.length) {
         System.out.println("Invalid array or index.");
         return arr;
      }
      
      // create new array of size-1
      int temp[] = new int[arr.length-1];
      
      // copy and skip at index
      for (int i = 0, j = 0; i < arr.length; i++) {
         if(i == index) {
            continue;
         }
         temp[j++] = arr[i];
      }

      return temp;
   }
}

Output:-

Original array: [10, 20, 30, 40, 50]
New array: [10, 20, 30, 50]

Using System.arraycopy()

The System.arraycopy() method is used to copy an array. Since it is a native method therefore it gives better performance compared to the loops.

public static native void arraycopy(Object src,  int  srcPos,
                    Object dest, int destPos, int length);

The arguments are:-
• src:- The source array.
• srcPos:- Starting position in the source array.
• dest:- The destination array.
• destPos:- starting position in the destination array.
• length:- the number of array elements to be copied.

This approach is similar to the previous one, but here we will use the System.arraycopy() method instead of loops. Here also the operations can be performed as,

a) Take an array and the index.
b) Create a new array with size 1 less than original array.
c) Copy elements of original array from 0 to index-1 to the new array.
d) Don’t copy the element at the specified index position.
e) Copy elements of original array from index+1 to end to the new array.
f) Return the copied new array.

The method can be written as,

// method to remove element at specific index using arraycopy()
public static int[] removeElement(int[] arr, int index) {

   // if array is null or index is negative or more then size 
   // return original array
   if(arr == null || index < 0 || index >= arr.length) {
      System.out.println("Invalid array or index.");
      return arr;
   }
   
   // create new array with size-1
   int temp[] = new int[arr.length-1];
   
   // copy from 0 to index-1
   System.arraycopy(arr, 0, temp, 0, index);

   // copy from index+1 to end
   System.arraycopy(arr, index+1, temp, index, arr.length-index-1);
      
   return temp;
}

With help of Java 8 Streams

Using the help of Java 8 stream also we can remove the element from array. For the we need to import java.util.stream.IntStream; In this approach,

a) Take an array and the index.
b) Convert the array into IntStream using IntStream.range() method.
c) Remove the element at specified index element using filter() method.
d) Map and form a new array of the filtered elements using map() and toArray() methods.
e) Return the formed array.

import java.util.Arrays;
import java.util.stream.IntStream;

public class ArrayTest {

   public static void main(String[] args) {
      int arr[] = { 10, 20, 30, 40, 50 };
      int index = 3; // index
      System.out.println("Original array: " + Arrays.toString(arr));
      arr = removeElement(arr, index);
      System.out.println("New array: " + Arrays.toString(arr));
   }

   // method to remove element at specific index 
   // using Java 8 Streams
   public static int[] removeElement(int[] arr, int index) {

      // if array is null or index is negative or more then size 
      // return original array
      if(arr == null || index < 0 || index >= arr.length) {
         System.out.println("Invalid array or index.");
         return arr;
      }
      
      // return the resultant array 
       return IntStream.range(0, arr.length) 
           .filter(i -> i != index) 
           .map(i -> arr[i]) 
           .toArray(); 
   }
}

Output:-

Original array: [10, 20, 30, 40, 50]
New array: [10, 20, 30, 50]

Using ArrayList

ArrayList also can be used to remove elements from the array in the Java programming language. In this approach,
a) Take an array and the index.
b) Convert array to ArrayList
c) Form an ArrayList with the array elements.
d) Remove the specified index element using the remove() method.
e) Form a new array of the ArrayList using mapToInt() and toArray() methods.
f) Return the formed array.

The below Java program demonstrate the above approach,

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class ArrayTest {

   public static void main(String[] args) {
      int arr[] = { 10, 20, 30, 40, 50 };
      int index = 2; // index
      System.out.println("Original array: " + Arrays.toString(arr));
      arr = removeElement(arr, index);
      System.out.println("New array: " + Arrays.toString(arr));
   }

   // method to remove element at specific index using ArrayList
   public static int[] removeElement(int[] arr, int index) {
      
      // if array is null or index is negative or more then size
      // return original array
      if (arr == null || index < 0 || index >= arr.length) {
         System.out.println("Invalid array or index.");
         return arr;
      }

      // Create ArrayList to Array
      List<Integer> list = IntStream.of(arr).boxed().
            collect(Collectors.toList());

      // remove the element from specified index
      list.remove(index);

      // return the resultant array
      return list.stream().
            mapToInt(Integer::intValue).toArray();

   }
}

Output:-

Original array: [10, 20, 30, 40, 50]
New array: [10, 20, 30, 50]

Remove Element From Array in Java by Value

To remove a specific element from an array, we need to find its index. After finding the index we can any of the above approaches to remove an element from an array at the specified index.

If the array is sorted then we can use the binary search (Arrays.binarySearch() method) else we can use linear search. Let us demonstrate it through linear search.

import java.util.Arrays;

public class ArrayTest {

   public static void main(String[] args) {

      // original array
      int arr[] = { 50, 20, 10, 40, 30 };

      // element to be removed
      int element = 40;

      // display old array
      System.out.println("Original array: " + Arrays.toString(arr));

      // remove specified element
      arr = removeElement(arr, element);

      // display new array
      System.out.println("New array: " + Arrays.toString(arr));
   }
   
   // method to remove specified element from array
   public static int[] removeElement(int[] arr, int element) {
      // find index
      int index = search(arr, element);
      
      // check index
      if(index == -1) {
         System.out.println("Element not found");
         return arr;
      }
      
      // remove element at specified index
      return removeAt(arr, index);
   }

   // linear search to return index of element
   public static int search(int[] arr, int element) {
      for (int i = 0; i < arr.length; i++) {
         if (arr[i] == element) {
            return i;
         }
      }
      return -1; // if element not found 
   }

   // method to remove element at specific index 
   // using System.arraycopy()
   public static int[] removeAt(int[] arr, int index) {
      
      // create new array with size-1
      int temp[] = new int[arr.length - 1];

      // copy from 0 to index-1
      System.arraycopy(arr, 0, temp, 0, index);

      // copy from index+1 to end
      System.arraycopy(arr, index + 1, temp, index, 
            arr.length - index - 1);

      return temp;
   }
}

Output:-

Original array: [50, 20, 10, 40, 30]
New array: [50, 20, 10, 30]

In this program, if the element which should be removed is having duplicates then only the first matched element will be removed and the remaining elements will be live as it is.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

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