Remove element from a specific index from an array in java

Let’s learn remove element from a specific index from an array in java.

Remove element from a specific index from an array in java

Now let’s learn to remove element from array by index. So to remove an element by index from an array first we have to find element at specified index and remove that element.

Then the remaining elements are copied to new array with size less than initial array. Here’s the program to remove element from a specific index from an array.

import java.util.Arrays;
public class RemoveElementDemo
{
   // remove element method 
   public static int[] removeElement(int[] arrGiven, int index) 
   {
      // if empty 
      if(arrGiven == null || index < 0 || index >= arrGiven.length) 
      {
         return arrGiven; 
      }
      // creating another array one less than initial array 
      int[] newArray = new int[arrGiven.length - 1];
      // copying elements except index 
      for(int a = 0, b = 0; a < arrGiven.length; a++) 
      { 
         if(a == index)
         {
            continue;
         }
         newArray[b++] = arrGiven[a]; 
      }
      return newArray; 
   }
   public static void main(String[] args) 
   { 
      int[] arrInput = { 2, 4, 6, 8, 10 };
      // printing given array 
      System.out.println("Given array: " + Arrays.toString(arrInput));
      // getting specified index 
      int index = 3;
      // print index 
      System.out.println("Index to be removed: " + index);
      // removing element 
      arrInput = removeElement(arrInput, index);
      // printing new array 
      System.out.println("New array: " + Arrays.toString(arrInput));
   }
}

Output:

Given array: [2, 4, 6, 8, 10]
Index to be removed: 3
New array: [2, 4, 6, 10]


Now let’s learn to remove element from a specific index from an array using Java8 streams.

import java.util.Arrays;
import java.util.stream.IntStream;
public class RemoveElementJava8Example
{
   public static int[] removeElement(int[] arrNum, int index)
   {
      // check if array is empty
      if(arrNum == null || index < 0 || index >= arrNum.length)
      {
         return arrNum;
      }
      return IntStream.range(0, arrNum.length)
              .filter(i -> i != index)
              .map(i -> arrNum[i])
              .toArray();
   }
   public static void main(String[] args)
   {
      int[] arrInput = { 2, 3, 4, 5, 6 };
      System.out.println("Given Array: " + Arrays.toString(arrInput));
      int index = 3;
      System.out.println("Remove element at index: " + index);
      arrInput = removeElement(arrInput, index);
      System.out.println("After removing element from an array: " + Arrays.toString(arrInput));
   }
}

Output:

Given Array: [2, 3, 4, 5, 6]
Remove element at index: 3
After removing element from an array: [2, 3, 4, 6]

Also read – major features of java