removeElements
is a static method of the ArrayUtils
class that removes instances of given elements from the provided array in the specified amounts. All items after the removal are moved to the left. There is no change, other than the removal of the existing matching items for any element-to-be-removed being supplied in higher quantities than those included in the original array.
If N
occurrences of an element have to be deleted from the array, repeat the element N
in the elements-to-be-removed array.
[1,2,3,4,5,2,3,2,2,4]
[2,2,2]
Applying the removeElements
function will result in the following array: [1,3,4,5,3,2,4]
.
As 2
is mentioned three times in the elements-to-be-removed
array, the first three occurrences of 2
are removed from the array.
[1,2,3,4,5,2,3,2,2,4]
[2,4,1,3]
Applying the removeElements
function will result in the following array: [5,2,3,2,2,4]
.
As every element is mentioned once in the elements-to-be-removed
array, the first occurrence of the elements are removed from 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[] removeElements(final int[] array, final int... values)
final int[] array
: the array from which the elements are to be removedfinal int... values
: the elements to be removedThis method returns a new array containing the existing elements, with the exception of the given elements’ earliest occurrences.
import org.apache.commons.lang3.ArrayUtils; public class Main { public static void main(String[] args) { int[] array = new int[]{1,2,3,4,5,2,3,2,2,4}; System.out.print("Original Array - "); for(int i: array){ System.out.print(i + " "); } int[] result = ArrayUtils.removeElements(array, 2,4,1,3); System.out.print("\nModified Array after removing elements - "); for(int i: result){ System.out.print(i + " "); } } }
Original Array - 1 2 3 4 5 2 3 2 2 4
Modified Array after removing elements - 5 2 3 2 2 4
RELATED TAGS
CONTRIBUTOR
View all Courses