Retrieving Elements from Collection in Java- Iterator


Following is an example to retrieve elements −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      HashSet<String> my_hs = new HashSet<String>() ;
      my_hs.add("Joe");
      my_hs.add ("Rob");
      Iterator my_it = my_hs.iterator();
      System.out.println("The elements are : ");
      while (my_it.hasNext())
         System.out.println(my_it.next());
   }
}

Output

The elements are :
Joe
Rob

A class named Demo contains the main function, which defines a HashSet collection. Elements are added to this collection using the ‘add’ function. An iterator is defined, and the elements are iterated over by checking if there is a next element with the help of the ‘hasNext’ function. The elements are displayed on the screen.

Updated on: 14-Sep-2020

267 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements