How to Remove Element from List In Java

Connect with

Oracle Java

I tried to demonstrate how to remove element from List in Java. There might be possibility to asked this question by interviewer in different way in your interview. How to remove any element from List, or its implementation class ArrayList, Vector, LinkedList or CopyOnArrayList. In a day-to-day development, you can found the situation where you have to remove item from List , based on the matching of value. So, you can use the following way in your real life project. If you don’t know how to iterate element from list in java, first visit provided link to understand how to iterate over ArrayList.

When you try to remove while iterating from same collection in same loop, you will encounter ConcurrentModificationException , it means your code throws Exception. To avoid exception i.e. ConcurrentModificationException , you can use Iterator’s remove method for removing/deleting from Collection/List( ArrayList , Vector, LinkedList ).

Remove element from List using Iterator

This is complete working example to remove object / element from List if matched .


package com.mysoftkey.collection;

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

/**
 * @author ranjeet jha
 *
 */
public class RemoveItemFromListExample {

  public static void main(String[] args) {
	List list = new ArrayList();
	list.add("java");
	list.add("Spring");
	list.add("Hibernate");
	list.add(".net");

	// print final list
	System.out.println("----- before removing of item --------");
	for (String name : list) {
	  System.out.println(name);
	}

	// remove name if ".net" string found in list.
	System.out.println("\n----- after removing of item --------");
	Iterator it = list.iterator();
	while (it.hasNext()) {
	  if (".net".equals(it.next())) {
		it.remove();
	  }
	}

	// print final list
	for (String name : list) {
	  System.out.println(name);
	}

  }

}

Output of Program


----- before removing of item --------
java
Spring
Hibernate
.net

----- after removing of item --------
java
Spring
Hibernate

Please write your comment/suggestion to improve this post. cheers Happy Learning 🙂


Connect with

1 thought on “How to Remove Element from List In Java

  1. Pingback: Anuj

Leave a Reply

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