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 we create one if condition where we compare which element want to remove from 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<>();

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

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

		// from Iterator remove method
		Iterator<String> itr = list.iterator();
		while (itr.hasNext()) {
			if ("N".equals( {
		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 *