javacodex.com
Java Examples
Java Examples
memu home questions

Removing elements from ArrayList using an Iterator

Use an Iterator to safely remove an element from a collection while iterating over ArrayList.

RemoveElement.java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
 
public class RemoveElement {
 
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(Arrays.asList("Paul", "Ringo", "George", "John"));
        System.out.println(names);
 
        Iterator<String> i = names.iterator();
        while (i.hasNext()) {
            String str = i.next();
            if(str.equals("Ringo")){
                i.remove();
            }
        }
 
        System.out.println(names);
    }
}
 

output

$ java RemoveElement
[Paul, Ringo, George, John]
[Paul, George, John]

Questions answered by this page:

Using Iterator to search an ArrayList and delete matching objects Removing element from ArrayList through Iterator Remove an element from Collection using Java Iterator How to Remove elements From ArrayList while Iterating




Contact: javacodex@yahoo.com