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

Comments

  1. Nice article . Thanks very much for sharing such good post. one more good java
    resource java collection tutorial

    ReplyDelete

Post a comment