How to remove an element from ArrayList in Java?

There are multiple way to remove an element from ArrayList in Java.
from for each method we first traverses each list element one by one and storing in string.after that we create if condition where comparing from equal method,if element found the call remove method.

from Java 8 removeIf method internally call java.util.function.Predicate method to compare element.its also handle concurrent modification exception.

from Iterator method first we iterate lis of element.then we call hasNext method to check next element is available.now we create one if condition where we compare which element want to remove from itr.next method.then call itr.remove method for removing element.

				
					import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class RemoveElementFromList {
	public static void main(String[] args) {
		List<String> list = new ArrayList<>();
		list.add("M");
		list.add("N");
		list.add("P");

		// from for Each method
		for (String s : list) {
			if (s.equals("N")) {
				list.remove(s);
			}
		}
		System.out.println("from For Each Method:- " + list);

		// From Java 8 removeIf method
		list.removeIf("N"::equals);
		System.out.println("from java 8 removeIf Method :- " + list);

		// from Iterator remove method
		Iterator<String> itr = list.iterator();
		while (itr.hasNext()) {
			if ("N".equals(itr.next())) {
				itr.remove();
			}
		}
		System.out.println("from iterator remove Method :-" + list);
	}
}
				
			

Output :-
from For Each Method:- [M, P]
from java 8 removeIf Method :- [M, P]
from iterator remove Method :-[M, P]

Leave a Comment

Your email address will not be published. Required fields are marked *