Remove all occurrences of an element from Array in Java
Given an array and a key, the task is to remove all occurrences of the specified key from the array in Java.
Examples:
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]
-
Using Arrays.copyOf:
// Java program remove all occurrences// of an element from Array using naive methodimportjava.util.Arrays;classGFG {// function to remove all occurrences// of an element from an arraypublicstaticint[] removeElements(int[] arr,intkey){// Move all other elements to beginningintindex =0;for(inti=0; i<arr.length; i++)if(arr[i] != key)arr[index++] = arr[i];// Create a copy of arr[]returnArrays.copyOf(arr, index);}// Driver codepublicstaticvoidmain(String[] args){int[] array = {3,9,2,3,1,7,2,3,5};intkey =3;array = removeElements(array, key);System.out.println(Arrays.toString(array));}}chevron_rightfilter_noneOutput:[9, 2, 1, 7, 2, 5]
-
Using Java 8 Stream:
- Get the array and the key.
- Filter all element of list which is equal to given key
- Convert the list back to an array and return it.
Below is the implementation of the above approach:
// Java program remove all occurrences// of an element from Array// Using Java 8 Stream APIimportjava.util.Arrays;classGFG {// function to remove all occurrences// of an element from an arraypublicstaticint[] removeElements(int[] arr,intkey){// return a new array except given keyreturnArrays.stream(arr).filter(val -> val != key).toArray();}// Driver codepublicstaticvoidmain(String[] args){// Get the arrayint[] array = {3,9,2,3,1,7,2,3,5};// Get the keyintkey =3;// Remove the keyarray = removeElements(array, key);// Print the modified arraySystem.out.println(Arrays.toString(array));}}chevron_rightfilter_noneOutput:[9, 2, 1, 7, 2, 5]
-
Using Java ArrayList:
- 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.
Below is the implementation of the above approach:
Program:
// Java program remove all occurrences// of an element from Array// Using Java ArrayListsimportjava.util.*;classGFG {// function to remove all occurrences// of an element from an arraypublicstaticint[] removeElements(int[] arr,intkey){// create an empty ArrayListList<Integer> result =newArrayList<Integer>();// insert all elements from the array into the list// except the specified keyfor(inti : arr) {if(i != key) {result.add(i);}}// convert the list back to an array and return itreturnresult.stream().mapToInt(Integer::intValue).toArray();}// Driver codepublicstaticvoidmain(String[] args){// Get the arrayint[] array = {3,9,2,3,1,7,2,3,5};// Get the keyintkey =3;// Remove the keyarray = removeElements(array, key);// Print the modified arraySystem.out.println(Arrays.toString(array));}}chevron_rightfilter_noneOutput:[9, 2, 1, 7, 2, 5]
-
Alternate Approach:
- First Create an List of Array.
- Remove all elements of the array into the list whose are the specified key.
- Convert the list back to an array and return its.
Below is the implementation of the above approach:
Program:
// Java program remove all occurrences// of an element from Array// Using Java Listimportjava.util.Arrays;importjava.util.List;importjava.util.stream.Collectors;importjava.util.stream.IntStream;classGFG {// function to remove all occurrences// of an element from an arraypublicstaticint[] removeElements(int[] arr,intkey){// Create a List// Insert all element of array into ListList<Integer> result = IntStream.of(arr)// IntStream.boxed().collect(Collectors.toList());// check every element if found then removefor(inti =0; i < result.size(); i++) {if(result.get(i).equals(key)) {result.remove(i--);}}// convert the list back to an array and return itreturnresult.stream().mapToInt(Integer::intValue).toArray();}// Driver codepublicstaticvoidmain(String[] args){// Get the arrayint[] array = {3,9,2,3,1,7,2,3,5};// Get the keyintkey =3;// Remove the keyarray = removeElements(array, key);// Print the modified arraySystem.out.println(Arrays.toString(array));}}chevron_rightfilter_noneOutput:[9, 2, 1, 7, 2, 5]
-
Using List.removeAll():
- First Create an empty List of Array.
- Insert all elements of the array into the list
- Remove all element which is you want to remove
- Convert the list back to an array and return its.
Below is the implementation of the above approach:
Program:
// Java program remove all occurrences// of an element from Arrayimportjava.util.*;importjava.util.stream.*;classGFG {// function to remove all occurrences of keypublicstaticint[] removeElements(int[] arr,intkey){// Create a List// Insert all element of array into ListList<Integer> result = IntStream.of(arr)// IntStream.boxed().collect(Collectors.toList());// remove all specific values and// an immutable set containing only the specified objectresult.removeAll(Collections.singleton(key));// sequential Stream over the elements in this collection// and return a new arrayreturnresult.stream().mapToInt(Integer::intValue).toArray();}// Driver codepublicstaticvoidmain(String[] args){// Get the arrayint[] array = {3,9,2,3,1,7,2,3,5};// Get the keyintkey =3;// Remove the keyarray = removeElements(array, key);// Print the modified arraySystem.out.println(Arrays.toString(array));}}chevron_rightfilter_noneOutput:[9, 2, 1, 7, 2, 5]
-
Using List.removeIf():
- First Create an empty List of Array.
- Insert all elements of the array into the list
- Remove all those element which is you want remove using equals() method
- Convert the list back to an array and return its.
Below is the implementation of the above approach:
Program:
// Java program remove all occurrences// of an element from Arrayimportjava.util.*;importjava.util.stream.*;classGFG {// function to remove all occurrences of keypublicstaticint[] removeElements(int[] arr,intkey){// Create a List// Insert all element of array into ListList<Integer> result = IntStream.of(arr)// IntStream.boxed().collect(Collectors.toList());// remove all specific values if matchresult.removeIf(n -> (n.equals(key)));// convert list into new array and returnreturnresult.stream().mapToInt(Integer::intValue).toArray();}// Driver codepublicstaticvoidmain(String[] args){// Get the arrayint[] array = {3,9,2,3,1,7,2,3,5};// Get the keyintkey =3;// Remove the keyarray = removeElements(array, key);// Print the modified arraySystem.out.println(Arrays.toString(array));}}chevron_rightfilter_noneOutput:[9, 2, 1, 7, 2, 5]
- Remove an Element at specific index from an Array in Java
- How to remove an element from ArrayList in Java?
- Find the index of an array element in Java
- How to Insert an element at a specific position in an Array in Java
- Pattern Occurrences : Stack Implementation Java
- Count occurrences of a given character using Regex in Java
- Java program to count the occurrences of each character
- Count occurrences of elements of list in Java
- Replace each element by the difference of the total size of the array and frequency of that element
- Replace every array element by Bitwise Xor of previous and next element
- Replace every element of the array by its previous element
- Replace every element of the array by its next element
- Remove duplicates from unsorted array
- Remove elements from the array which appear more than k times
- Remove elements from the array whose frequency lies in the range [l, r]
Recommended Posts:
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



