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]
  1. Using Arrays.copyOf:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

    Output:



    [9, 2, 1, 7, 2, 5]
    
    1. Using Java 8 Stream:

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

      Below is the implementation of the above approach:

      filter_none

      edit
      close

      play_arrow

      link
      brightness_4
      code

      // Java program remove all occurrences
      // of an element from Array
      // Using Java 8 Stream API
        
      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)
          {
        
              // return a new array except given key
              return Arrays.stream(arr)
                  .filter(val -> val != key)
                  .toArray();
          }
        
          // Driver code
          public static void main(String[] args)
          {
        
              // Get the array
              int[] array = { 3, 9, 2, 3, 1, 7, 2, 3, 5 };
        
              // Get the key
              int key = 3;
        
              // Remove the key
              array = removeElements(array, key);
        
              // Print the modified array
              System.out.println(Arrays.toString(array));
          }
      }

      chevron_right

      
      

      Output:

      [9, 2, 1, 7, 2, 5]
      
    2. 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.

      Below is the implementation of the above approach:

      Program:

      filter_none

      edit
      close

      play_arrow

      link
      brightness_4
      code

      // Java program remove all occurrences
      // of an element from Array
      // Using Java ArrayLists
        
      import java.util.*;
        
      class GFG {
        
          // function to remove all occurrences
          // of an element from an array
          public static int[] removeElements(int[] arr, int key)
          {
        
              // create an empty ArrayList
              List<Integer> result = new ArrayList<Integer>();
        
              // insert all elements from the array into the list
              // except the specified key
              for (int i : arr) {
                  if (i != key) {
                      result.add(i);
                  }
              }
        
              // convert the list back to an array and return it
              return result.stream()
                  .mapToInt(Integer::intValue)
                  .toArray();
          }
        
          // Driver code
          public static void main(String[] args)
          {
        
              // Get the array
              int[] array = { 3, 9, 2, 3, 1, 7, 2, 3, 5 };
        
              // Get the key
              int key = 3;
        
              // Remove the key
              array = removeElements(array, key);
        
              // Print the modified array
              System.out.println(Arrays.toString(array));
          }
      }

      chevron_right

      
      

      Output:

      [9, 2, 1, 7, 2, 5]
      
    3. Alternate Approach:

      1. First Create an List of Array.
      2. Remove all elements of the array into the list whose are the specified key.
      3. Convert the list back to an array and return its.
      4. Below is the implementation of the above approach:

        Program:

        filter_none

        edit
        close

        play_arrow

        link
        brightness_4
        code

        // Java program remove all occurrences
        // of an element from Array
        // Using Java List
          
        import java.util.Arrays;
        import java.util.List;
        import java.util.stream.Collectors;
        import java.util.stream.IntStream;
          
        class GFG {
          
            // function to remove all occurrences
            // of an element from an array
            public static int[] removeElements(int[] arr, int key)
            {
          
                // Create a List
                // Insert all element of array into List
                List<Integer> result = IntStream.of(arr) // IntStream
                                           .boxed()
                                           .collect(Collectors.toList());
          
                // check every element if found then remove
                for (int i = 0; i < result.size(); i++) {
                    if (result.get(i).equals(key)) {
                        result.remove(i--);
                    }
                }
          
                // convert the list back to an array and return it
                return result.stream()
                    .mapToInt(Integer::intValue)
                    .toArray();
            }
          
            // Driver code
            public static void main(String[] args)
            {
          
                // Get the array
                int[] array = { 3, 9, 2, 3, 1, 7, 2, 3, 5 };
          
                // Get the key
                int key = 3;
          
                // Remove the key
                array = removeElements(array, key);
          
                // Print the modified array
                System.out.println(Arrays.toString(array));
            }
        }

        chevron_right

        
        

        Output:

        [9, 2, 1, 7, 2, 5]
        
      5. Using List.removeAll():

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

        Below is the implementation of the above approach:

        Program:

        filter_none

        edit
        close

        play_arrow

        link
        brightness_4
        code

        // Java program remove all occurrences
        // of an element from Array
          
        import java.util.*;
        import java.util.stream.*;
          
        class GFG {
          
            // function to remove all occurrences of key
            public static int[] removeElements(int[] arr, int key)
            {
          
                // Create a List
                // Insert all element of array into List
                List<Integer> result = IntStream.of(arr) // IntStream
                                           .boxed()
                                           .collect(Collectors.toList());
          
                // remove all specific values and
                // an immutable set containing only the specified object
                result.removeAll(Collections.singleton(key));
          
                // sequential Stream over the elements in this collection
                // and return a new array
                return result.stream()
                    .mapToInt(Integer::intValue)
                    .toArray();
            }
          
            // Driver code
            public static void main(String[] args)
            {
          
                // Get the array
                int[] array = { 3, 9, 2, 3, 1, 7, 2, 3, 5 };
          
                // Get the key
                int key = 3;
          
                // Remove the key
                array = removeElements(array, key);
          
                // Print the modified array
                System.out.println(Arrays.toString(array));
            }
        }

        chevron_right

        
        

        Output:

        [9, 2, 1, 7, 2, 5]
        
      6. 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 remove using equals() method
        4. Convert the list back to an array and return its.

        Below is the implementation of the above approach:

        Program:

        filter_none

        edit
        close

        play_arrow

        link
        brightness_4
        code

        // Java program remove all occurrences
        // of an element from Array
          
        import java.util.*;
        import java.util.stream.*;
          
        class GFG {
          
            // function to remove all occurrences of key
            public static int[] removeElements(int[] arr, int key)
            {
          
                // Create a List
                // Insert all element of array into List
                List<Integer> result = IntStream.of(arr) // IntStream
                                           .boxed()
                                           .collect(Collectors.toList());
          
                // remove all specific values if match
                result.removeIf(n -> (n.equals(key)));
          
                // convert list into new array and return
                return result.stream()
                    .mapToInt(Integer::intValue)
                    .toArray();
            }
          
            // Driver code
            public static void main(String[] args)
            {
          
                // Get the array
                int[] array = { 3, 9, 2, 3, 1, 7, 2, 3, 5 };
          
                // Get the key
                int key = 3;
          
                // Remove the key
                array = removeElements(array, key);
          
                // Print the modified array
                System.out.println(Arrays.toString(array));
            }
        }

        chevron_right

        
        

        Output:

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


      My Personal Notes arrow_drop_up

      Strategy Path planning and Destination matters in success No need to worry about in between temporary failures

      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.