- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- Iterate through elements of HashSet in Java
- Get Enumeration over HashSet in Java
- Java Program to Iterate over enum
- Add elements to HashSet in Java
- Count the number of elements in a HashSet in Java
- Iterate through elements of TreeSet in Java
- How to iterate over a list in Java?
- Iterate through elements of Java LinkedHashSet
- How to iterate over a Java list?
- Java Program to Iterate over an ArrayList
- Java Program to Iterate over a HashMap
- Java Program to Iterate over a Set
- Remove duplicate elements in Java with HashSet
- Remove all elements from a HashSet in Java
- What are the different ways to iterate over an array in Java?

Advertisements