Thursday, April 20, 2023

How to iterate over HashSet in Java - loop or traverse Example

Iterating over HashSet in Java
Java program to Iterate over HashSet in Java with ExampleIn our last Java collection tutorial, we have seen How to iterate over ArrayList in Java and in this tutorial we will see How to iterate over HashSet in Java. There are two ways to iterate, loop or traverse over HashSet in Java, first using advanced for-each loop added on Java 5 and second using Iterator which is a more conventional way of iterating over HashSet in Java. Now questions are When should you use for loop and when Iterator is an appropriate option. Well I usually use for loop If I only read from HashSet and doesn't remove any element, while Iterator is preferred approach. You should not remove elements from HashSet while iterating over it in for loop, Use Iterator to do that.



Iterating over HashSet in Java - Example

In this section, we will see the code example of iterating over HashSet in Java. We have created HashSet and added a couple of String on HashSet and when we iterate, we will print those String one by one in the console.



/**
 *
 * Java program to Iterate, loop or traverse over HashSet in Java
 * This technique can be used to traverse over any other Collection as well
 * e.g. traversing over ArrayList or traversing over LinkedList in Java
 * @author
 */

public class IteratorTest {

 
    public static void main(String args[]) {
     
        //creating HashSet to iterate over
        Set<String> streams = new HashSet<String>();
        streams.add("Programming");
        streams.add("Development");
        streams.add("Debugging");
        streams.add("Coding");
     
        // Iterating over HashSet in Java using for-each loop
        for(String str : streams){
            System.out.println(" Looping over HashSet in Java element : " + str);
        }
     
        //Iterating over HashSet using Iterator in Java
        Iterator<String> itr = streams.iterator();
        while(itr.hasNext()){
            System.out.println(" Iterating over HashSet in Java current object: " + itr.next());
        }
     
    }
}

Output:
 Looping over HashSet in Java element : Coding
 Looping over HashSet in Java element : Programming
 Looping over HashSet in Java element : Debugging
 Looping over HashSet in Java element : Development
 Iterating over HashSet in Java current object: Coding
 Iterating over HashSet in Java current object: Programming
 Iterating over HashSet in Java current object: Debugging
 Iterating over HashSet in Java current object: Development


That's all on How to iterate over HashSet in Java. Use for each loop if you are just reading from collection and not removing any object from HashSet.

Other Java Collection Tutorial from Java67 Blog

2 comments:

Feel free to comment, ask questions if you have any doubt.