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.
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
.
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.
ArrayUtils
is defined in theApache Commons Lang
package.Apache Commons Lang
can be added to the Maven Project by adding the following dependency to thepom.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[] removeElement(final int[] array, final int element)
final int[] array
is the array from which the element has to be removed.final int element
is the element to be removed.The method returns a new array with the first occurrence of the element removed.
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 + " ");}}}
Original Array - 1 2 3 4 5
Modified Array after removing element 4 - 1 2 3 5