This post will discuss how to remove all occurrences of the specified element from a primitive integer array in Java.

We know that arrays in Java are not dynamic, unlike an ArrayList, and one cannot simply remove an element from it. However, one can create a new array from the original array containing the desired elements and return it. This post provides an overview of some of the available alternatives to accomplish this.

1. Using Java 8 Stream

The recommended approach is to use the Stream for this task. The idea is first to convert the given array into the stream and filter all occurrences of the specified element using the filter() method. Finally, we convert the stream back to an array using the toArray() method.

Download  Run Code

Output:

[1, 3, 4, 4, 5]

2. Using ArrayList

Another plausible way of removing all occurrences of the specified element from the specified array involves using a list data structure.

  1. Create an empty ArrayList.
  2. Insert all array elements into the list except the specified key.
  3. Convert the list back to an array and return it.

Download  Run Code

Output:

[1, 3, 4, 4, 5]

 
Here’s another alternative approach using a list:

  1. Insert all elements from the array into a list.
  2. Remove all occurrences of the specified key from the list using its removeAll() method.
  3. Convert the list back to an array and return it.

Download  Run Code

Output:

[1, 3, 4, 4, 5]

3. Using Apache Commons Lang

Another good alternative is to leverage Apache Commons ArrayUtils class, which provides the removeAllOccurences() method for this purpose.

Download Code

That’s all about removing all occurrences of the specified element from an array in Java.