VOOZH about

URL: https://www.geeksforgeeks.org/java/remove-all-occurrences-of-an-element-from-array-in-java/

⇱ Remove all Occurrences of an Element from Array in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Remove all Occurrences of an Element from Array in Java

Last Updated : 11 Jul, 2025

In Java, removing all occurences of a given element from an array can be done using different approaches that are,

  • Naive approach using array copy
  • Java 8 Streams
  • Using ArrayList.removeAll()
  • Using List.removeIf()

Problem Stament: Given an array and a key, the task is to remove all occurrences of the specified key from the array in Java.

Examples to Remove Elements Occurrences in Array:

Input: array = { 3, 9, 2, 3, 1, 7, 2, 3, 5 }, key = 3
Output: [9, 2, 1, 7, 2, 5]

Input: array = { 10, 20, 10, 30, 50, 10 }, key = 10
Output: [20, 30, 50]

Illustration: In this example, we will remove all occurrences of an element from an array using the Arrays.copyOf method.


Output
[9, 2, 1, 7, 2, 5]

Complexity of the above method:

  • Time Complexity: O(n)
  • Space Complexity: O(n)

Java Program to Remove All Occurrences of an Element from Array

1. Using Java 8 Stream

Approach:

  • Get the array and the key.
  • Filter all elements of the list which is equal to a given key
  • Convert the list back to an array and return it.

Illustration: Here, we will use the Java 8 streams to remove all occurrences of an element from an array.


Output
[9, 2, 1, 7, 2, 5]


2. Using Java ArrayList

Approach:

  • Get the array and the key.
  • Create an empty ArrayList.
  • Insert all elements from the array into the list except the specified key
  • Convert the list back to an array and return it.

Alternative Approach:

  • First, create a List of arrays.
  • Remove all elements of the array into the list that are the specified key.
  • Convert the list back to an array and return it.

Illustration: Using the ArrayList to remove all occurrences of an element from an array.


Output
[9, 2, 1, 7, 2, 5]


3. Using List.removeAll()

Approach:

  • First, create a list from the array.
  • Insert all elements of the array into the list
  • Remove all elements that match the given key.
  • Convert the list back to an array and return it.

Illustration: Using the List.removeAll() to remove all occurrences of an element from an array.


Output
[9, 2, 1, 7, 2, 5]


4. Using List.removeIf()

Approach:

  • First Create an empty List of Array.
  • Insert all elements of the array into the list.
  • Remove all those elements which is you want to remove using the equals() method.
  • Convert the list back to an array and return it.

Illustration: Using the List.removeIf() to remove all occurrences of an element from an array.


Output
[9, 2, 1, 7, 2, 5]
Comment