- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Traverse through a HashSet in Java
HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage.
A hash table stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code.
To traverse through a HashSet, you can use the Iterator in Java. At first, create a HashSet with string values −
HashSet<String> hashSet = new HashSet(); hashSet.add("Jack"); hashSet.add("Tom"); hashSet.add("David"); hashSet.add("John"); hashSet.add("Steve");
Now, traverse using Iterator −
Iterator<String> iterator = hashSet.iterator(); while(iterator.hasNext()){ System.out.println(iterator.next()); }
Let us see a simple example wherein we have some HashSet elements and we would be traversing each of them and displaying −
Example
import java.util.*; class Main{ public static void main(String args[]){ HashSet<String> hashSet = new HashSet(); hashSet.add("Jack"); hashSet.add("Tom"); hashSet.add("David"); hashSet.add("John"); hashSet.add("Steve"); hashSet.add("Kevin"); hashSet.add("Ryan"); hashSet.add("Lyn"); Iterator<String> iterator = hashSet.iterator(); System.out.println("HashSet elements..."); while(iterator.hasNext()) { System.out.println(iterator.next()); } } }
Output
HashSet elements... Lyn Kevin Tom Ryan Steve David John Jack
- Related Articles
- Traverse through a HashMap in Java
- Iterate through elements of HashSet in Java
- HashSet in Java
- Initialize HashSet in Java
- Initializing HashSet in Java
- The HashSet in Java
- How to create a HashSet in Java?
- Getting an enumerator that iterates through HashSet in C#
- Importance of HashSet in Java
- Traverse TreeSet elements in descending order in java
- Remove all elements from a HashSet in Java
- Remove single element from a HashSet in Java
- Check for an element in a HashSet in Java
- Different ways to traverse an Array in Java?
- Get size of HashSet in Java

Advertisements