How to Delete Element From Array In Java ?

In this article we will see how to delete element from array using Java ? OR how to remove element from array using Java ? There are two things here. 1) You can delete element from array by providing its index. 2) You can delete element from array by providing its value. Here we will cover both the things. We will see usage of apache commons lang3 library and we will also see how to remove element from array using Java 8 ? Java 8 provides array stream with which we can delete element from array by providing value.

Lets first add apache commons lang3 library using Apache Maven.


                <dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.11</version>
		</dependency>

Now lets see how to use this library to remove element from array and we will also see how to use Java 8 stream to delete element from array.

import java.util.Arrays;
import org.apache.commons.lang3.ArrayUtils;

public class ArrayDeletion {

	public static void main(String[] args) {
		
		String[] str = {"1", "2", "3", "4", "3"};
		
		// removing by index
		str = ArrayUtils.remove(str, 1);
		
		// removing by value
		str = ArrayUtils.removeElement(str, "3");
		
		// using java 8
		str = Arrays.stream(str).filter(s -> !s.equals("3")).toArray(String[] :: new);
		
		for (String s : str) {
			System.out.println(s);
		}
		
	}

}

One thing you need to remember is that when you are using apache commons lang3 library to delete an element by value then it will just delete the 1st occurrence of that value NOT all. If you want to remove all occurrences of the value then use Java 8 stream.

0 Comments