Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Retrieving Elements from Collection in Java- Iterator
Following is an example to retrieve elements −
Example
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.
Advertisements