List (ArrayList) Iterator Example

In this example, we will write a Java code to iterate over an ArrayList using the Iterator interface.

List (ArrayList) Iterator Example

Here is the example to iterate over an ArrayList using Iterator interface:
package com.java.tutorials.collections;

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

/**
 * Iterator Examples
 * @author Ramesh Fadatare
 *
 */
public class IteratorExample {
    public static void main(String[] args) {
  
        List<String> fruits = new ArrayList<String>();
        fruits.add("Banana");
        fruits.add("Apple");
        fruits.add("Mango");
        fruits.add("Orange");
  
        Iterator<String> iterator = fruits.iterator();
           while (iterator.hasNext()) {
           String fruit = (String) iterator.next();
           System.out.println(fruit);
   
          if("Banana".equals(fruit)) {
              iterator.remove();
          }
       }
       System.out.println(fruits);
    }
}
Output:
Banana
Apple
Mango
Orange
[Apple, Mango, Orange]

Reference

Java ArrayList Source Code Examples

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course

Comments