Iterable

Implementing this interface allows an object to be the target of the "foreach" statement.

ReturnMethodSummary
Iterator<T>iterator()Returns an iterator over a set of elements of type T.

import java.util.Iterator;
import java.util.LinkedList;

public class Main{
    public static void main(String args[]) {
        LinkedList<String> ll = new LinkedList<String>();

        ll.add("A");
        ll.add("ja v a2s.com");
        ll.addLast("B");
        ll.add("C");

        Iterator<String> itr = ll.iterator();
        while (itr.hasNext()) {
            String element = itr.next();
            System.out.print(element + " ");
        }
    }
}
  

The output:


A ja v a2s.com B C

Remove an element from Collection using Iterator


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

public class Main {
  public static void main(String[] args) {
    ArrayList aList = new ArrayList();
    aList.add("1");
    aList.add("2");
    aList.add("3");
    aList.add("4");
    aList.add("java2 s .com");
    System.out.println("ArrayList: ");
    System.out.println(aList);
    Iterator itr = aList.iterator();
    String strElement = "";
    while (itr.hasNext()) {
      strElement = (String) itr.next();
      if (strElement.equals("2")) {
        itr.remove();
        break;
      }
    }
    System.out.println("ArrayList after removal : ");
    System.out.println(aList);
  }
}

The output:


ArrayList: 
[1, 2, 3, 4, java2 s .com]
ArrayList after removal : 
[1, 3, 4, java2 s .com]
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.