Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to Remove Duplicate Elements From Java LinkedList?
Next article icon

How to Remove an Element from Collection using Iterator Object in Java?

Last Updated : 07 Jan, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Collection in Java is a set of interfaces like List, Set, and Queue. An iterator in Java is used to iterate or traverse through the elements of the Collection. There are three types of iterator in Java namely, Enumerator, Iterator, and ListIterator. 

The two ways of removing an element from Collections using Iterator :

  1. Using Iterator
  2. Using ListIterator

Approach 1: Using Iterator

  • A List is created and elements are added to the list using the add() method.
  • The Iterator object is used to iterate over the elements of the list using the hasNext() and next() methods.
  • An if the condition is used within the while loop and when the condition is satisfied, the particular element is removed using the remove() method.
  • When the entire list is traversed again the element which was removed is no longer present in the list.
Java
// Java program to Remove an Element from  // Collection using Iterator   import java.util.ArrayList; import java.util.Iterator; class IteratorDemo  {     public static void main(String[] args)      {         ArrayList<Integer> l = new ArrayList<Integer>();                for(int i=0;i<=50;i=i+5)         {             l.add(i);         }                Iterator<Integer> itr = l.iterator();                System.out.println("List before removal");                for(int i=0;i<l.size();i++)         {             System.out.print(l.get(i)+" ");         }                  while(itr.hasNext())         {             if(itr.next()%2==1)                 itr.remove();         }              System.out.println("\nList after removal");                for(int i=0;i<l.size();i++)         {             System.out.print(l.get(i)+" ");         }     }  } 

Output
List before removal  0 5 10 15 20 25 30 35 40 45 50   List after removal  0 10 20 30 40 50

Approach 2: Using ListIterator

  • A list is created and elements are added to the list using the add() method.
  • The ListIterator object is used to iterate over the elements of the list using the hasNext() and next() methods.
  • An if condition is used within the while loop and when the condition is satisfied, the particular element is removed using the remove() method.
  • When the entire list is traversed again the element which was removed is no longer present in the list.
Java
// Java program to Remove an Element from // Collection using ListIterator  import java.util.ArrayList; import java.util.ListIterator;  public class ListIteratorDemo {     public static void main(String[] args)     {         ArrayList<String> l = new ArrayList<String>();          l.add("January");         l.add("February");         l.add("March");         l.add("April");         l.add("May");         l.add("June");         l.add("July");         l.add("August");          ListIterator<String> itr = l.listIterator();          System.out.println("List before removal");          for (int i = 0; i < l.size(); i++)             System.out.print(l.get(i) + " ");          while (itr.hasNext()) {             if (itr.next().equals("March")) {                 itr.remove();             }         }          System.out.println("\nList after removal");          for (int i = 0; i < l.size(); i++)             System.out.print(l.get(i) + " ");     } } 

Output
List before removal  January February March April May June July August   List after removal  January February April May June July August

Next Article
How to Remove Duplicate Elements From Java LinkedList?

S

Shreyasi_Chakraborty
Improve
Article Tags :
  • Java
  • Technical Scripter
  • Java Programs
  • Technical Scripter 2020
  • Java-Collections
  • Java-Iterator
Practice Tags :
  • Java
  • Java-Collections

Similar Reads

  • Java Program to Remove an Element from ArrayList using ListIterator
    ListIterator.remove() method removes the last element from the list that was returned by next() or previous() cursor positions. It can be called only once per call to next or previous. It can be made only if the operation — add(E) has not called after the last call to next or previous. Internal work
    4 min read
  • Java Program to Remove a Specific Element From a Collection
    remove() method is used to remove elements from a collection. It removes the element at the specified position in this list. Shifts any subsequent elements to the left by subtracts one from their indices. In simpler words, the remove() method is used for removing the element from a specific index fr
    3 min read
  • How to Remove Elements from a LinkedHashMap in Java?
    A LinkedHashMap is a part of the Collection Framework from java.util package Java and is similar to a HashMap, except that a LinkedHashMap preserves the insertion order among the keys/entries. In this article, we will look at how to remove the elements from a LinkedHashMap in Java. Program to Remove
    2 min read
  • How to Insert all the Collection Elements to the Specified Position in Java ArrayList?
    The element can be inserted at the collection elements to the specified position in ArrayList using Collection.addAll() method which is present in java.util.ArrayList class. If any element present at the index then that element and all its right side elements are shifted to the right side. this meth
    3 min read
  • How to Remove Duplicate Elements From Java LinkedList?
    Linked List is a part of the Collection in java.util package. LinkedList class is an implementation of the LinkedList data structure it is a linear data structure. In LinkedList due to the dynamical allocation of memory, insertions and deletions are easy processes. For removing duplicates from Examp
    4 min read
  • Removing last element from ArrayList in Java
    Given an ArrayList collection in Java, the task is to remove the last element from the ArrayList. Example: Input: ArrayList[] = [10, 20, 30, 1, 2] Output: [10, 20, 30, 1] After removing the last element 2, the ArrayList is: [10, 20, 30, 1] Input: ArrayList[] = [1, 1, 2, 2, 3] Output: [1, 1, 2, 2] Af
    2 min read
  • Replace an Element From ArrayList using Java ListIterator
    To replace an element from an ArrayList, the set() method of ListIterator interface can be used. set() method of ListIterator replaces the last element which is returned by the next() or previous() methods, along with the given element. Two ways of replacing the elements using ListIterator shown bel
    3 min read
  • How to Delete User Defined Objects from LinkedHashSet?
    The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the elements
    2 min read
  • How to Iterate over the Elements of a PriorityQueue in Java?
    In Java, a Priority Queue is a Data structure that allows the users to store data based on their priority so that the elements with the highest priority can be accessed in constant time. In this article, we will learn how to iterate over the elements of a PriorityQueue in Java. Example Input: Priori
    2 min read
  • Java Program To Remove All The Duplicate Entries From The Collection
    As we know that the HashSet contains only unique elements, ie no duplicate entries are allowed, and since our aim is to remove the duplicate entries from the collection, so for removing all the duplicate entries from the collection, we will use HashSet.The HashSet class implements the Set interface,
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences