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
Iterate over the elements of HashSet in Java
Declare a HashSet and add elements −
Set hs = new HashSet(); hs.add(20); hs.add(39); hs.add(67); hs.add(79);
Now, iterate over the elements −
for (Iterator i = hs.iterator(); i.hasNext();) {
Object ele = i.next();
System.out.println(ele);
}
The following is an example that iterate over the elements of HashSet −
Example
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class Demo {
public static void main(String[] argv) throws Exception {
Set hs = new HashSet();
hs.add(20);
hs.add(39);
hs.add(67);
hs.add(79);
System.out.println("Elements = ");
for (Iterator i = hs.iterator(); i.hasNext();) {
Object ele = i.next();
System.out.println(ele);
}
}
}
Output
Elements = 67 20 39 79
Advertisements