Since Set interface or HashSet class doesn't provide a get() method to retrieve elements, the only way to take out elements from a Set is to iterate over it by using the Iterator, or loop over Set using advanced for loop of Java 5. You can get the iterator by calling the iterator() method of the Set interface. This method returns an iterator over the elements in the sets but they are returned in no particular order, as Set doesn't guarantee any order. Though individual Set implementations e.g. LinkedHashSet or TreeSet can impose ordering and in such iterator will return elements on that order.
You can only traverse in one direction using iterator i.e. from first to last elements, there is no backward traversing allowed as was the case with List interface and ListIterator. Similarly, if you use advanced for loop, then also you can traverse in only one direction.
In this tutorial, you will learn both ways to traverse over Set or HashSet in Java i.e. by using both Iterator and enhanced for loop. Btw, Java 8 also introduced a new to loop over a set, that is by using the forEach() method if you are lucky to be running on Java 8 then you can use that as well.
And, If you are new to the Java world then I also recommend you go through The Complete Java MasterClass on Udemy to learn Java in a better and more structured way. This is one of the best and up-to-date courses to learn Java online.
Here are the steps to traverse over as Set using Iterator in Java:
This will print all the stocks from the setOfStocks into the console.
There is another forEach() method defined in the Stream class from the new JDK 8 Stream API, See 10 ways to use forEach in Java 8 for more examples.
Here is the summary of all three ways to iterate over HashSet or any Set in Java:
You can only traverse in one direction using iterator i.e. from first to last elements, there is no backward traversing allowed as was the case with List interface and ListIterator. Similarly, if you use advanced for loop, then also you can traverse in only one direction.
In this tutorial, you will learn both ways to traverse over Set or HashSet in Java i.e. by using both Iterator and enhanced for loop. Btw, Java 8 also introduced a new to loop over a set, that is by using the forEach() method if you are lucky to be running on Java 8 then you can use that as well.
And, If you are new to the Java world then I also recommend you go through The Complete Java MasterClass on Udemy to learn Java in a better and more structured way. This is one of the best and up-to-date courses to learn Java online.
Iterating over Set using Iterator
Here are the steps to traverse over as Set using Iterator in Java:
- Obtain the iterator by calling the iterator() method.
- You can use while or for loop along with hasNext(), which returns true if there are more elements in the Set.
- Call the next() method to obtain the next elements from Set.
Iterator<String> itr = setOfStocks.iterator(); // traversing over HashSet System.out.println("Traversing over Set using Iterator"); while(itr.hasNext()){ System.out.println(itr.next()); }
Loop over HashSet using for loop
There are no particular steps to loop over Set using enhanced for loop, as you just need to use the Set as per loop construct as shown below:for(String stock : setOfStocks){ System.out.println(stock); }
This will print all the stocks from the setOfStocks into the console.
Traversing over HashSet using forEach() method
This method is only available from Java 8 onwards. This forEach() method belongs to Iterable interface and since Set implements that you can use this to traverse over Set as shown below:public class HashSetLooperJava8{ public static void main(String args[]) { // Creating and initializing an HashSet for iteration Set<String> setOfBooks = new HashSet<>(); setOfBooks.add("Effective Java"); setOfBooks.add("Clean Code"); setOfBooks.add("Refactoring"); setOfBooks.add("Head First Java"); setOfBooks.add("Clean Coder"); // iterating over HashSet using forEach() method in Java 8 setOfBooks.forEach(System.out::println); } } Output: Clean Code Effective Java Head First Java Clean Coder Refactoring
There is another forEach() method defined in the Stream class from the new JDK 8 Stream API, See 10 ways to use forEach in Java 8 for more examples.
Here is the summary of all three ways to iterate over HashSet or any Set in Java:
Java Program to loop over HashSet in Java
Here is a sample program to show you how you can loop over a Set in Java using both Iterator and advanced for loop. The only difference in the two ways is that you can remove elements while iterating using Iterator's remove() method but you cannot remove elements while looping over HashSet using enhanced for loop, even though Set provides a remove() method. Doing so will result in ConcurrentModificationException in Java.import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class HashSetDemo { public static void main(String args[]) { // Creating and initializing an HashSet for iteration Set<String> setOfStocks = new HashSet<>(); setOfStocks.add("INFY"); setOfStocks.add("BABA"); setOfStocks.add("GOOG"); setOfStocks.add("MSFT"); setOfStocks.add("AMZN"); System.out.println("Set: " + setOfStocks); // Example 1 - iterating over HashSet using Iterator // Obtaining the Iterator Iterator<String> itr = setOfStocks.iterator(); // traversing over HashSet System.out.println("Traversing over Set using Iterator"); while (itr.hasNext()) { System.out.println(itr.next()); } // Example 2 - looping over HashSet using for loop System.out.println("Looping over HashSet using advanced for loop"); for (String stock : setOfStocks) { System.out.println(stock); } } } Output: Set: [AMZN, INFY, MSFT, GOOG, BABA] Traversing over Set using Iterator AMZN INFY MSFT GOOG BABA Looping over HashSet using advanced for loop AMZN INFY MSFT GOOG BABA
That's all about how to traverse over HashSet or Set in Java. You can use the same technique to loop over other Set implementations like LinkedHashSet, TreeSet, EnumSet, CopyOnWriteHashSet or ConcurrentSkipListSet in Java.
All these implementations provide the iterator() method which returns the elements in the order this class individually guarantees like LinkedHashSet guarantees insertion order and TreeSet guarantees the sorted order imposed by Comparable or Comparator provided while creating TreeSet instance.
You can choose between Iterator and advanced for loop to traverse over Set depending upon whether you want to remove the elements during iterator or not. The iterator allows you to remove elements but enhanced for loop doesn't allow that.
2 comments :
which one should one prefer?
@Anonymous, use Iterator if you want to remove elements, otherwise enhanced for loop looks more readable. Use forEach() method if you are writing code in Java 8.
Post a Comment