array list iterator

PHOTO EMBED

Fri Jun 07 2024 12:20:07 GMT+0000 (Coordinated Universal Time)

Saved by @dbms

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

public class ArrayListIteratorExample {
    public static void main(String[] args) {
        // Create an ArrayList and add some fruit names
        ArrayList<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        
        // Obtain an iterator for the ArrayList
        Iterator<String> iterator = fruits.iterator();
        
        // Use the iterator to traverse through the ArrayList
        System.out.println("Using Iterator to traverse through the ArrayList:");
        while (iterator.hasNext()) {
            String fruit = iterator.next();
            System.out.println(fruit);
        }
        
        // Use a for-each loop to traverse through the ArrayList
        System.out.println("\nUsing for-each loop to traverse through the ArrayList:");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
        
        // Obtain a new iterator for the ArrayList
        iterator = fruits.iterator(); // Reset the iterator
        while (iterator.hasNext()) {
            String fruit = iterator.next();
            if (fruit.startsWith("B")) {
                iterator.remove(); // Remove elements that start with "B"
            }
        }
        
        // Display the ArrayList after removal of elements that start with 'B'
        System.out.println("\nArrayList after removal of elements that start with 'B':");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}
content_copyCOPY