What is ArrayUtils.removeElement in java?
removeElement is a static method of the ArrayUtils class that removes the first occurrence of an element in the given array. All the subsequent elements are shifted by one position to the left in the array once the element is removed.
Example 1
- Array = [1,2,3,2,4,5].
- Element = 2.
The array [1,3,2,4,5] is the result of the application of the removeElement function.
The first occurrence of the element 2 is at index 1. All the subsequent elements are shifted by one position to the left in the array once the element is removed from the index 1.
Example 2
- Array = [1,2,3,4,5].
- Offset = 10.
The array [1,2,3,4,5] is a result of the application of the removeElement function.
The array is returned as it is because the element is not found in the array.
ArrayUtilsis defined in theApache Commons Langpackage.Apache Commons Langcan be added to the Maven Project by adding the following dependency to thepom.xmlfile.
<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
ArrayUtilsclass as follows.
import org.apache.commons.lang3.ArrayUtils;
Syntax
public static int[] removeElement(final int[] array, final int element)
Parameters
final int[] arrayis the array from which the element has to be removed.final int elementis the element to be removed.
Returns
The method returns a new array with the first occurrence of the element removed.
Code
import org.apache.commons.lang3.ArrayUtils;public class Main {public static void main(String[] args) {int[] array = {1,2,3,4,5};System.out.print("Original Array - ");for(int i: array){System.out.print(i + " ");}int[] result = ArrayUtils.removeElement(array, 4);System.out.print("\nModified Array after removing element 4 - ");for(int i: result){System.out.print(i + " ");}}}
Expected output
Original Array - 1 2 3 4 5
Modified Array after removing element 4 - 1 2 3 5