Learn example of how to remove element from List in Java using for iterator and while loop.
1. Overview to Remove Element from List In Java
I tried to cover the example of how to remove elements from List in Java. In a day-to-day development, you can found the situation where you have to remove items from List
, based on the matching of value. So, you can use the following way in your real-life project.
If you are learner and don’t know how to iterate element from list in java, first visit this link to understand how to iterate
over ArrayList
.
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
.
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
).
2. 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) { Listlist = 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); } } }
3. Output of Program
----- before removing of item -------- java Spring Hibernate .net ----- after removing of item -------- java Spring Hibernate
4. Reference
I hope you enjoyed this post remove element from java.util.List
in Java using Iterator
, you can visit visit Core Java tutorial for more blog post.
Please write your suggestions to improve this post. Happy Learning! 🙂
Pingback: Anuj