There are following two ways to iterate through HashSet
:
1) Using Iterator
2) Without using Iterator
Example 1: Using Iterator
import java.util.HashSet; import java.util.Iterator; class IterateHashSet{ public static void main(String[] args) { // Create a HashSet HashSet<String> hset = new HashSet<String>(); //add elements to HashSet hset.add("Chaitanya"); hset.add("Rahul"); hset.add("Tim"); hset.add("Rick"); hset.add("Harry"); Iterator<String> it = hset.iterator(); while(it.hasNext()){ System.out.println(it.next()); } } }
Output:
Chaitanya Rick Harry Rahul Tim
Example 2: Iterate without using Iterator
import java.util.HashSet; import java.util.Set; class IterateHashSet{ public static void main(String[] args) { // Create a HashSet Set<String> hset = new HashSet<String>(); //add elements to HashSet hset.add("Chaitanya"); hset.add("Rahul"); hset.add("Tim"); hset.add("Rick"); hset.add("Harry"); for (String temp : hset) { System.out.println(temp); } } }
Output:
Chaitanya Rick Harry Rahul Tim
Witty says
Hello!
Can I ask you a question?
Is there any difference in declarations in 1st and 2nd examples:
HashSet hset = new HashSet(); and
Set hset = new HashSet();
Taiwo Azeez A says
Technically, yes, for the 1st line, you are coding to an implementation while for the 2nd line, you are coding to an interface. In otherwords, hashset is a concrete class while the Seet is an interface
tedd says
It is always a good idea to put the interface name on the left side from good software engineering practices. It hides implementation details.