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
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
Advertisements