How do you remove elements during Iteration

How do you remove elements during Iteration

Answer: Iterator interface provides method to remove element from Collection during iteration. Please see java example below:

package com.javahonk.iteratorenumeration;

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

public class IntratorRemoveTest {

	public static void main(String[] args) {

	List<String> arrayList = new ArrayList<String>();

	arrayList.add("Java");
	arrayList.add("Honk");
	arrayList.add("Monk");

	Iterator<String> iterator = arrayList.iterator();
	System.out.println("Origional List");
	while (iterator.hasNext()) {
		String string = (String) iterator.next();
		System.out.println(string);
		if (string.equalsIgnoreCase("Monk")) {
			iterator.remove();
		}
	}

	iterator = arrayList.iterator();
	System.out.println("\nAfter remove");
	while (iterator.hasNext()) {
		String string = (String) iterator.next();
		System.out.println(string);
	}

	}

}

 

Output:

How do you remove elements during Iteration

 

Leave a Reply

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