The iterator() method of Java AbstractCollection class

Java 8Object Oriented ProgrammingProgramming

The iterator() method of the AbstractCollection class in Java is used to return an iterator over the elements contained in this collection.

The syntax is as follows −

public abstract Iterator<E> iterator()

To work with AbstractCollection class in Java, import the following package −

import java.util.AbstractCollection;

For Iterator, import the following package −

import java.util.Iterator;

The following is an example to implement the AbstractCollection iterator() method in Java −

Example

 Live Demo

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

public class Demo {
   public static void main(String[] args) {
      AbstractCollection<Object> absCollection = new ArrayList<Object>();
      absCollection.add("Laptop");
      absCollection.add("Tablet");
      absCollection.add("Mobile");
      absCollection.add("E-Book Reader");
      absCollection.add("SSD");
      absCollection.add("HDD");
      System.out.println("AbstractCollection = " + absCollection);
      System.out.println("Iterating elements one by one...");
      Iterator i = absCollection.iterator();
      while (i.hasNext()) {
         System.out.println(i.next());
      }
   }
}

Output

AbstractCollection = [Laptop, Tablet, Mobile, E-Book Reader, SSD, HDD]
Iterating elements one by one...
Laptop
Tablet
Mobile
E-Book Reader
SSD
HDD
raja
Published on 27-Mar-2019 13:17:12
Advertisements