- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Use Iterator to remove an element from a Collection in Java
An element can be removed from a Collection using the Iterator method remove(). This method removes the current element in the Collection. If the remove() method is not preceded by the next() method, then the exception IllegalStateException is thrown.
A program that demonstrates this is given as follows.
Example
import java.util.ArrayList; import java.util.Iterator; public class Demo { public static void main(String[] args) { ArrayList<String> aList = new ArrayList<String>(); aList.add("Apple"); aList.add("Mango"); aList.add("Guava"); aList.add("Orange"); aList.add("Peach"); System.out.println("The ArrayList elements are: "); for (String s: aList) { System.out.println(s); } Iterator i = aList.iterator(); String str = ""; while (i.hasNext()) { str = (String) i.next(); if (str.equals("Orange")) { i.remove(); System.out.println("
The element Orange is removed"); break; } } System.out.println("
The ArrayList elements are: "); for (String s: aList) { System.out.println(s); } } }
Output
The output of the above program is as follows
The ArrayList elements are: Apple Mango Guava Orange Peach The element Orange is removed The ArrayList elements are: Apple Mango Guava Peach
- Related Articles
- Retrieving Elements from Collection in Java- Iterator
- Iterate through a Collection using an Iterator in Java
- Iterator vs Collection in Java
- Remove an element from a Queue in Java
- Remove an element from a Stack in Java
- How to remove an element from a Java List?
- Remove an element from IdentityHashMap in Java
- How to remove an element from an array in Java
- How to remove an element from ArrayList in Java?
- Java Program to Remove Repeated Element from An ArrayList
- How to use Iterator in Java?
- How to remove an element from ArrayList or, LinkedList in Java?
- Java Program to remove an element from List with ListIterator
- Remove an element from an ArrayList using the ListIterator in Java
- How to remove all elements from a Collection in another Collection

Advertisements