This post will discuss how to remove a specific element from an array in Java.

Arrays in Java have fixed lengths. This means they hold a fixed number of values of a single type. The length of an array is decided upon its creation. After creation, its length is fixed.

Since the array length is fixed, there is no standard way to remove elements from it. However, you can create a new array containing all the original array elements except the one which you want to remove. There are several ways to achieve that in Java:

1. Using Apache Commons Lang Library

The Apache Commons Lang’s ArrayUtils class offers the removeElement() method to remove the first occurrence of the specified element from the specified array. It is overloaded to accept all primitive types and object arrays. Following is a simple example demonstrating its usage.

Download Code

Output:

[2, 5, 7, 3, 8, 9]

2. Using Java 8

You can also leverage Stream API to remove an element from an array. The idea is to convert the array into a sequential stream, filter the stream to remove the given element, and accumulate the remaining elements into a new array using a collector.

Download  Run Code

Output:

[2, 5, 7, 3, 8, 9]

 
Here’s a working example for an array of objects, which uses the equals() method:

Download  Run Code

Output:

[A, B, D]

3. Convert To List

Another solution is to convert the array into a list and then remove the given element using List’s remove() method. Finally, convert the list back to the array of the same type. This solution is not recommended as it involves the creation of an intermediary list object.

Download  Run Code

Output:

[A, B, D]

 
In case you need to remove all instances of the specific element, you can use List’s removeAll() method.

Download  Run Code

Output:

[A, B, D]

4. Remove by index

If you have the index of the element to be removed, you can use the System.arraycopy() method to ensure better performance. The idea is to allocate a new array of size one less than the original array. Then, you can make two calls to the System.arraycopy() to copy the array elements into the new array before and after that index.

Download  Run Code

Output:

[A, B, C, D]

That’s all about removing specific elements from an array in Java.