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
// Java program remove all occurrences// of an element from Array using naive methodÂ
import java.util.Arrays;Â
class GFG {Â
    // function to remove all occurrences    // of an element from an array    public static int[] removeElements(int[] arr, int key)    {        // Move all other elements to beginning        int index = 0;        for (int i=0; i<arr.length; i++)            if (arr[i] != key)                arr[index++] = arr[i];Â
        // Create a copy of arr[]        return Arrays.copyOf(arr, index);    }Â
    // Driver code    public static void main(String[] args)    {        int[] array = { 3, 9, 2, 3, 1, 7, 2, 3, 5 };        int key = 3;        array = removeElements(array, key);        System.out.println(Arrays.toString(array));    }} |
[9, 2, 1, 7, 2, 5]
Time Complexity: O(n)
Space Complexity: O(n)
Using Java 8 Stream:
- Get the array and the key.
- Filter all element of the list which is equal to a given key
- Convert the list back to an array and return it.
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.
Alternate Approach:
- First Create a List of Array.
- Remove all elements of the array into the list that are the specified key.
- Convert the list back to an array and return it.
Using List.removeAll():
- First Create an empty List of Array.
- Insert all elements of the array into the list
- Remove all elements which is you want to remove
- Convert the list back to an array and return it.
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 to remove using the equals() method
- Convert the list back to an array and return it.
