In this article, we will discuss various ways to iterate through HashSet – 3 ways
Different ways to iterate through HashSet:
- Enhanced for-loop introduced in Java 1.5 version
- Iterating using Iterator of Collection interface
- Iterating Set using forEach() in Java 8
DifferentWaysToIterateHashSet.java
package in.bench.resources.java.collections;
import java.util.HashSet;
import java.util.Iterator;
public class DifferentWaysToIterateHashSet {
public static void main(String[] args) {
// creating HashSet object of type String
HashSet<String> hset = new HashSet<String>();
// adding elements to HashSet object
hset.add("Sundar Pichai");
hset.add("Satya Nadella");
hset.add("Shiv Nadar");
hset.add("Shantanu Narayen");
hset.add("Sundar Pichai"); // duplicate object
hset.add("Francisco D’Souza");
// Way 1: Iterating using enhanced for-loop
System.out.println("Way 1: Iterating using "
+ "enhanced for-loop\n");
for(String str : hset) {
System.out.println(str);
}
// Way 2: Iterating using Iterator of Collection interface
System.out.println("\n\nWay 2: Iterating using Iterator "
+ "of Collection interface\n");
Iterator<String> itr = hset.iterator();
while(itr.hasNext()) {
System.out.println(itr.next());
}
}
}
Output:
Way 1: Iterating using enhanced for-loop
Sundar Pichai
Shantanu Narayen
Shiv Nadar
Francisco D’Souza
Satya Nadella
Way 2: Iterating using Iterator of Collection interface
Sundar Pichai
Shantanu Narayen
Shiv Nadar
Francisco D’Souza
Satya Nadella
From above example, HashSet
- doesn’t allow duplicate elements
- maximum of one null object is allowed
- while iterating, retrieve elements in random order
In the next article, we will see a demo example on how to iterate Set using Stream in Java 1.8 i.e.;
Related Articles:
To conclude, now there are 3 ways to iterate Set
- Java – Various ways to iterate through ArrayList
- Java – Various ways to iterate through Vector – 5 ways
- Java – Various ways to iterate through LinkedList – 5 ways
- Java – Various ways to iterate through HashSet – 3 ways
- Java – How to reverse LinkedHashSet contents ?
- Java – Various ways to iterate through TreeSet – 3 ways
- Java – Various ways to iterate over List of HashMap
- Java – Ways to iterate over HashMap of ArrayList
- Java – Various ways to iterate Arrays – 5 ways
- Java 8 – Iterating Set using forEach() method
References:
- https://docs.oracle.com/javase/tutorial/collections/intro/
- https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
- https://docs.oracle.com/javase/tutorial/collections/interfaces/set.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Set.html
- https://docs.oracle.com/javase/7/docs/api/java/util/class-use/HashSet.html
- https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html
- https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
Happy Coding !!
Happy Learning !!