In this article, we will discuss various ways to iterate through HashSet – 3 ways
Various ways to iterate through HashSet:
- Enhanced for-loop introduced in Java 1.5 version
- Iterating using Iterator of Collection interface
Example: Various ways to iterate through HashSet
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.;
To conclude, now there are 3 ways to iterate Set
- Enhanced for-loop (introduced in Java 1.5 version)
- Iterating using Iterator of Collection interface
- Iterating Set using forEach() in Java 8
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/7/docs/api/java/util/Iterator.html
- https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
Happy Coding !!
Happy Learning !!