CodesJava

Easy learning with example program codes

How to remove element from collection using iterator?


We can use iterator interface. It is a universal iterator as we can apply it to any Collection object. It provides the functionality of read and remove operations. Collection interface provides iterator() method to get the Iterator object. Iterator interface have following to methods to remove collection objects.

hasNext(): It returns true if the iteration has more elements.
next(): It returns the next element in the iteration.
remove(): It will remove the last element returned by the iterator.

Example:

package com.codesjava;
 
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
public class Test {
  public static void main(String args[]){
	String removeElement = "Vivek";
	List<String> list = new ArrayList<String>();
	list.add("Jai");
	list.add("Vivek");
	list.add("Mahesh");
	list.add("Vishal");
	list.add("Hemant");
	System.out.println("Before remove:");
        System.out.println(list);
        Iterator<String> iterator = list.iterator();
        while(iterator.hasNext()){
        	if(removeElement.equals(iterator.next())){
        		iterator.remove();
            }
        }
        System.out.println("After remove:");
        System.out.println(list);
  }
}

Output

Before remove:
[Jai, Vivek, Mahesh, Vishal, Hemant]
After remove:
[Jai, Mahesh, Vishal, Hemant]


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap