Open In App

Remove all occurrences of an element from Array in Java

Last Updated : 22 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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]

Program to Remove all occurrences of an element from Array

Below is the implementation using Arrays.copyOf of above Program:

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[] a, int k) 
    { 
        // Move all other elements to beginning 
        int index = 0; 
        for (int i=0; i<a.length; i++) 
            if (a[i] != k) 
                a[index++] = a[i]; 

        // Create a copy of arr[] 
        return Arrays.copyOf(a, index); 
    } 

    // Driver code 
    public static void main(String[] args) 
    { 
        int[] a = { 3, 9, 2, 3, 1, 7, 2, 3, 5 }; 
        int k = 3; 
        a = removeElements(a, k); 
        System.out.println(Arrays.toString(a)); 
    } 
} 

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

Complexity of the above method:

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


Other Methods to Remove all occurrences of an element from Array

1. Using Java 8 Stream

Approach to Implement the Method:

  • 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.

Program Implementation for the Approach:

Java
// Java program remove all occurrences 
// of an element from Array using Stream
import java.util.Arrays;

public class RemoveElement {
    public static void main(String[] args) {
        // Example array
        Integer[] a = { 3, 9, 2, 3, 1, 7, 2, 3, 5 }; 

        // Element to be removed
        int k = 3;

        // Remove all occurrences of the element using Java 8 Stream
        Integer[] newArr = Arrays.stream(a)
                .filter(e -> e != k)  // Filter out the element to remove
                .toArray(Integer[]::new);           // Collect result into a new array

        // Print the result
        System.out.println(Arrays.toString(newArr));
    }
}

Output
Array after removal: [9, 2, 1, 7, 2, 5]


2. Using Java ArrayList

Approach to Implement the ArrayList Method:

  • 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.

Program Implementation for the Approach:

Java
// Java program remove all occurrences 
// of an element from Array using ArrayList 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

// Driver Class
public class RemoveElementUsingArrayList {
      // Main Method
    public static void main(String[] args) {
        
        Integer[] a = { 3, 9, 2, 3, 1, 7, 2, 3, 5 }; 

        // Element to be removed
        Integer k = 3;

        // Convert array to ArrayList
        List<Integer> list = new ArrayList<>(Arrays.asList(a));

        // Remove all occurrences of the element
        list.removeAll(Arrays.asList(k));

        // Convert ArrayList back to array
        Integer[] newArr = list.toArray(new Integer[0]);

        // Print the result
        System.out.println(Arrays.toString(newArr));
    }
}

Output
Array after removal: [9, 2, 1, 7, 2, 5]


3. 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.

Program Implementation for the Approach:

Java
// Java program remove all occurrences 
// of an element from Array using List.removeAll 
import java.util.*;

// Driver Class
public class RemoveElementUsingRemoveAll {
    // Main Method
      public static void main(String[] args) {
        // Example array
        Integer[] a = { 3, 9, 2, 3, 1, 7, 2, 3, 5 };

        // Element to be removed
        Integer k = 3;

        // Convert array to List (using ArrayList to allow modification)
        List<Integer> list = new ArrayList<>(Arrays.asList(a));

        // Remove all occurrences of the element
        list.removeAll(Arrays.asList(k));

        // Convert List back to array
        Integer[] newArr = list.toArray(new Integer[0]);

        // Print the result
        System.out.println(Arrays.toString(newArr));
    }
}

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


4. 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.

Program Implementation for the Approach:

Java
// Java program remove all occurrences 
// of an element from Array using removeIf()
import java.util.*;

// Driver Class
public class RemoveElementUsingRemoveIf {
      // Main Method
    public static void main(String[] args) {
        // Example array
        Integer[] a = { 3, 9, 2, 3, 1, 7, 2, 3, 5 };

        // Element to be removed
        int k = 3;

        // Convert array to List (using ArrayList to allow modification)
        List<Integer> list = new ArrayList<>(Arrays.asList(a));

        // Remove all occurrences using removeIf()
        list.removeIf(e -> e == k);

        // Convert List back to array
        Integer[] newArr = list.toArray(new Integer[0]);

        // Print the result
        System.out.println(Arrays.toString(newArr));
    }
}

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




Previous Article
Next Article

Similar Reads

Remove an Element at Specific Index from an Array in Java
Given an array of a fixed length. The task is to remove an element at a specific index from the array. Examples: Input: arr[] = { 1, 2, 3, 4, 5 }, index = 2 Output: arr[] = { 1, 2, 4, 5 } Input: arr[] = { 4, 5, 9, 8, 1 }, index = 3 Output: arr[] = { 4, 5, 9, 1 } An array is a data structure that contains a group of elements. Typically these element
7 min read
Pattern Occurrences : Stack Implementation Java
Suppose we have two Strings :- Pattern and Text pattern: consisting of unique characters text: consisting of any lengthWe need to find the number of patterns that can be obtained from text removing each and every occurrence of Pattern in the Text. Example: Input : Pattern : ABC Text : ABABCABCC Output : 3 Occurrences found at: 4 7 8 Explanation Occ
12 min read
How to remove an element from ArrayList in Java?
ArrayList is a part of collection framework and is present in java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. This class is found in java.util package. With the introduction and upgradations in java versions
4 min read
Remove all elements from the ArrayList in Java
Prerequisite: ArrayList in Java Given an ArrayList, the task is to remove all elements of the ArrayList in Java. Examples: Input: ArrayList = [1, 2, 3, 4] Output: ArrayList = [] Input: ArrayList = [12, 23, 34, 45, 57, 67, 89] Output: ArrayList = [] Using clear() method: Syntax: collection_name.clear(); Code of clear() method: public void clear() {
2 min read
Different Ways to Remove all the Digits from String in Java
Given alphanumeric string str, the task is to write a Java program to remove all the digit from this string and prints the modified string. Examples: Input: str = “GeeksForGeeks123”Output: GeeksForGeeksExplanation: The given string contains digits 1, 2, and 3. We remove all the digit and prints the modified string. Input: str = “12Java”Output: Java
3 min read
How to remove given object from an Array in Java?
Given an array arr of N objects, the task is to remove all the occurrences of a given object from the array in Java. Example: Input: String[] arr = { "Geeks", "for", "Geeks", "hello", "world" }, removeObj = "Geeks" Output: updated arr[] = {"for", "hello", "world"}Explanation: All the occurrences of removeObj has been removed from the array. Methods
3 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Maximum element in an array such that its previous and next element product is maximum
Given an array arr[] of N integers, the task is to print the largest element among the array such that its previous and next element product is maximum.Examples: Input: arr[] = {5, 6, 4, 3, 2} Output: 6 The product of the next and the previous elements for every element of the given array are: 5 -> 2 * 6 = 12 6 -> 5 * 4 = 20 4 -> 6 * 3 = 1
6 min read
Queries to print count of distinct array elements after replacing element at index P by a given element
Given an array arr[] consisting of N integers and 2D array queries[][] consisting of Q queries of the form {p, x}, the task for each query is to replace the element at position p with x and print the count of distinct elements present in the array. Examples: Input: Q = 3, arr[] = {2, 2, 5, 5, 4, 6, 3}, queries[][] = {{1, 7}, {6, 8}, {7, 2}}Output:
14 min read
TreeSet remove() Method in Java
The Java.util.TreeSet.remove(Object O) method is to remove a particular element from a Tree set. Syntax: TreeSet.remove(Object O) Parameters: The parameter O is of the type of Tree set and specifies the element to be removed from the set. Return Value: This method returns True if the element specified in the parameter is initially present in the Se
1 min read
EnumMap remove() Method in Java
The Java.util.EnumMap.remove(key) method in Java is used to remove the specified key from the map. Syntax: remove(Object key) Parameters: The method takes one parameter key which refers to the key whose mapping is to be removed. Return Value: The method does not return any value. Below programs illustrate the working of remove(key) function: Progra
2 min read
LinkedList remove() Method in Java
LinkedList as we all know is a way of storing data that contains sets of nodes where each node contains data and address part where address part is responsible for linking of nodes and hence forming a List over which now we can perform operations. Now here we want to remove a node/s using the remove() method of LinkedList class only. Illustration:
4 min read
HashSet remove() Method in Java
HashSet remove() method is used to remove a particular element from a HashSet. Note that it is only after JDK version 1.2 and ahead, and will throw compilation errors before in version JDK 1 and JDK1.1. Note: This method returns true if the specified element is present in the HashSet otherwise it returns boolean false. Syntax: HashSet.remove(Object
2 min read
PriorityQueue remove() Method in Java
The remove() method of PriorityQueue class of java.util package is used to remove a particular element from a PriorityQueue. As we all know that the elements while entering into the priority queue are not sorted but as we all know while taking out elements from the priority queue the elements are always sorted being a trait of the priority queue. H
5 min read
HashMap remove() Method in Java
The java.util.HashMap.remove() is an inbuilt method of HashMap class and is used to remove the mapping of any particular key from the map. It basically removes the values for any particular key in the Map.Syntax: Hash_Map.remove(Object key) Parameters: The method takes one parameter key whose mapping is to be removed from the Map.Return Value: The
2 min read
TreeMap remove() Method in Java
The java.util.TreeMap.remove() is an inbuilt method of TreeMap class and is used to remove the mapping of any particular key from the map. It basically removes the values for any particular key in the Map. Syntax: Tree_Map.remove(Object key) Parameters: The method takes one parameter key whose mapping is to be removed from the Map. Return Value: Th
2 min read
ArrayDeque remove() Method in Java
The Java.util.ArrayDeque.remove() method is used to remove the element present at the head of the Deque. Syntax: Array_Deque.remove() Parameters: The method does not take any parameters. Return Value: This method returns the element present at the head of the Deque. Exceptions: The method throws NoSuchElementException is thrown if the deque is empt
3 min read
WeakHashMap remove() method in Java
The java.util.WeakHashMap.remove() is an inbuilt method of WeakHashMap class and is used to remove the mapping of any particular key from the map. It basically removes the values for any particular key in the Map. Syntax: Weak_Hash_Map.remove(Object key) Parameters: The method takes one parameter key whose mapping is to be removed from the Map. Ret
2 min read
ArrayBlockingQueue remove() method in Java
ArrayBlockingQueue is bounded, blocking queue that stores the elements internally backed by an array. ArrayBlockingQueue class is a member of the Java Collections Framework. Bounded means it will have a fixed size, you can not store number the elements more than the capacity of the queue. The queue also follows FIFO (first-in-first-out) rule for st
3 min read
IdentityHashMap remove() Method in Java
The java.util.IdentityHashMap.remove() is an inbuilt method of IdentityHashMap class and is used to remove the mapping of any particular key from the map. It basically removes the values for any particular key in the Map. Syntax: Identity_Hash_Map.remove(Object key) Parameters: The method takes one parameter key whose mapping is to be removed from
2 min read
Vector remove() Method in Java
remove(int index) The java.util.vector.remove(int index) method is used to remove an element from a Vector from a specific position or index. Syntax: Vector.remove(int index) Parameters: This method accepts a mandatory parameter index is of integer data type and specifies the position of the element to be removed from the Vector. Return Value: This
2 min read
LinkedBlockingQueue remove() method in Java
The remove(Object obj) method of LinkedBlockingQueue removes only one instance of the given Object, passed as parameter, from this LinkedBlockingQueue if it is present. It removes an element e such that obj.equals(e) and if this queue contains one or more instance of element e. This method returns true if this queue contained the element which is n
4 min read
PriorityBlockingQueue remove() method in Java
The remove(Object o) method of PriorityBlockingQueue is used to delete an element from this queue. This method removes a single instance of the element passed as the parameter, if it is present. It returns true if and only if the element was removed, else it returned false. Syntax: public boolean remove(Object o) Parameter: This method accepts a ma
2 min read
ConcurrentHashMap remove() method in Java
The remove() method in Java's ConcurrentHashMap class is used to remove the entry for a given key from the map. It has the following signature: V remove(Object key)where: key is the key of the entry to be removed.V is the type of values in the map.The remove() method works in a concurrent environment, which means that multiple threads can access an
7 min read
LinkedTransferQueue remove() method in Java
The java.util.concurrent.LinkedTransferQueue.remove() method is an in-built function in Java which is used to remove an element if it is present in this queue. Syntax: LinkedTransferQueue.remove(Object o) Parameters: The function accepts a single parameter o i.e. the object to be removed. Return Value: The function returns a true boolean value on s
2 min read
ConcurrentSkipListSet remove() method in Java
The java.util.concurrent.ConcurrentSkipListSet.remove() method is an in-built function in Java which is used to remove an element if it is present in this set. Syntax: ConcurrentSkipListSet.remove(Object o) Parameters: The function accepts a single parameter o i.e. the object to be removed. Return Value: The function returns a true boolean value on
2 min read
LinkedBlockingDeque remove() method in Java
The remove() method of LinkedBlockingDeque removes the head of the Deque container. The method throws a NoSuchElementException if the Deque container is empty. Syntax: public E remove() Parameters: This method does not accepts any parameter. Returns: This method does not returns anything. Exception: The function throws a NoSuchElementException if t
2 min read
Remove elements from a List that satisfy given predicate in Java
Below are the methods to efficiently remove elements from a List satisfying a Predicate condition: p ==> Predicate, specifying the condition l ==> List, from which element to be removed Using iterator Below program demonstrates the removal of null elements from the list, using the Predicate Java Code // Java Program to remove nulls // from a
5 min read
Queue remove() method in Java
The remove() method of Queue Interface returns and removes the element at the front of the container. It deletes the head of the container. The method throws an NoSuchElementException when the Queue is empty. Syntax: E remove() Returns: This method returns the head of the Queue. Exception: The function throws an NoSuchElementException when the Queu
3 min read
Java program to remove nulls from a List Container
List is an ordered collection of objects which allows to store duplicate values or null values, in the insertion order. So it is very important to remove null values in many scenarios. Examples: Input: [Geeks, null, forGeeks, null, A computer portal] Output: [Geeks, forGeeks, A computer portal] Input: [1, null, 2, 3, null, 4] Output: [1, 2, 3, 4] B
6 min read
three90RightbarBannerImg