removeAllOccurrences
is a static method of the ArrayUtils
class that removes all the occurrences of an element in the given array. All the subsequent elements are shifted to the left in the array once all the occurrences are removed.
[1,2,3,2,4,5]
2
The array [1,3,4,5]
is a result of applying the removeAllOccurrences
function.
All occurrences of the element 2
are removed and the subsequent elements are shifted to the left in the array.
[1,2,3,2,4,5]
-2
The array [1,2,3,2,4,5]
is a result of applying the removeAllOccurrences
function.
The array is returned as it is because the element is not found in the array.
ArrayUtils
is defined in the Apache Commons Lang package. Apache Commons Lang can be added to the Maven project by adding the following dependency to the pom.xml
file.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the commons-lang package, refer to the Maven Repository.
You can import the ArrayUtils
class as follows:
import org.apache.commons.lang3.ArrayUtils;
public static int[] removeAllOccurrences(final int[] array, final int element)
final int[] array
- the array from which the element has to be removed.final int element
- element to be removed.import org.apache.commons.lang3.ArrayUtils;public class Main {public static void main(String[] args) {int[] array = {1,2,3,4,5,4,2,3,2,4,5};System.out.print("Original Array - ");for(int i: array){System.out.print(i + " ");}int[] result = ArrayUtils.removeAllOccurrences(array, 4);System.out.print("\nModified Array after removing element 4 - ");for(int i: result){System.out.print(i + " ");}}}
Original Array - 1 2 3 4 5 4 2 3 2 4 5
Modified Array after removing element 4 - 1 2 3 5 2 3 2 5