Saturday, December 28, 2024
Google search engine
HomeLanguagesJavaRemove all occurrences of an element from Array in Java

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




// 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));
    }
}


Output:

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

Time Complexity: O(n)

Space Complexity: O(n)

Using Java 8 Stream:

  1. Get the array and the key.
  2. Filter all element of the list which is equal to a given key
  3. Convert the list back to an array and return it.

Using Java ArrayList:

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

Alternate Approach:

  1. First Create a List of Array.
  2. Remove all elements of the array into the list that are the specified key.
  3. Convert the list back to an array and return it.

Using List.removeAll():

  1. First Create an empty List of Array.
  2. Insert all elements of the array into the list
  3. Remove all elements which is you want to remove
  4. Convert the list back to an array and return it.

Using List.removeIf():

  1. First Create an empty List of Array.
  2. Insert all elements of the array into the list
  3. Remove all those element which is you want to remove using the equals() method
  4. Convert the list back to an array and return it.
Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments