Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
array
communitycreator

What is ArrayUtils.removeElements in Java?

abhilash

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.

Example 1

  • array = [1,2,3,4,5,2,3,2,2,4]
  • elements-to-be-removed: [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.

Example 2

  • array = [1,2,3,4,5,2,3,2,2,4]
  • elements-to-be-removed: [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;

Syntax

public static int[] removeElements(final int[] array, final int... values)

Parameters

  • final int[] array: the array from which the elements are to be removed
  • final int... values: the elements to be removed

Returns

This method returns a new array containing the existing elements, with the exception of the given elements’ earliest occurrences.

Code

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 + " ");
        }
    }
}

Expected output

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

java
array
communitycreator
RELATED COURSES

View all Courses

Keep Exploring