The iterator() method of Java AbstractCollection class


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

Updated on: 30-Jul-2019

75 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements