Skip to main content

Different ways to iterate HashSet in java

How to Iterate HashSet in java

In this article, we are going to learn about how to iterate HashSet in java. Java provides various ways to loop over the HashSet that we are going to see one-by-one.

What is HashSet in java?

HashSet in java is an implementation of the Set interface of Java. A Set is similar to a List but duplicate elements are not allowed in a Set. To know more about the HashSet, visit this article: HashSet in java

How to iterate HashSet in java using Iterator?

HashSet provides a method called iterator() which returns an object of Iterator. Iterator is an interface defined in java.util package and its implementation are provided by the HashSet internally.
Look at the Syntax of how to get the object of Iterator from the HashSet:
Syntax of iterator() method
Iterator<T> iterator = hashSet.iterator();
By using this iterator object, we can iterate HashSet in java. Iterator provides two methods to iterate HashSet in java are:
  • hasNext() : returns true, if iterator has more elements for iteration.
  • next() : returns the next element from the Iterator.
With the combination of these two methods, we can iterate HashSet in java.

Java HashSet Iterator Example 1: Iterate HashSet using Iterators

HashSet<String> bookSet = new HashSet<>();
bookSet.add("Programming In Java");
bookSet.add("Introduction to Algorithms");
bookSet.add("Data Structures");
bookSet.add("Learn C++");
bookSet.add("Computer Networks");

Iterator<String> iterator = bookSet.iterator();

while (iterator.hasNext()) {
      String nextElement = iterator.next();
      System.out.println(nextElement);
}
Output
Programming In Java
Introduction to Algorithms
Data Structures
Learn C++
Computer Networks

Exceptional Case

Any addition or deletion of elements onto the HashSet during the Iteration is not allowed. In such cases, java.util.ConcurrentModificationException will be raised. Just look at the example:
Iterator<String> iterator = bookSet.iterator();

while (iterator.hasNext()) {
      String nextElement = iterator.next();

      // ConcurrentModificationException will be raised 
      bookSet.add("Add new Element to the List"); 

      System.out.println(nextElement);
}
Output
Exception in thread "main" java.util.ConcurrentModificationException
        at java.util.HashSet$Itr.checkForComodification(HashSet.java:909
        at java.util.HashSet$Itr.next(HashSet.java:859)
        at prac.code.HashSetExample.main(HashSetExample.java:56)

How to iterate HashSet in java using for each loop?

HashSet in java implements Iterable Interface and any class whose implements Iterable interface can be iterate using for-each loop. Let's look at the example:

Java HashSet Iterator Example 2: Iterate HashSet using for-each loop

for(String book : bookSet){
      System.out.println(book);
}

Output
Programming In Java
Introduction to Algorithms
Data Structures
Learn C++
Computer Networks
Note: Similar to Iterators, Any Addition or Modification of the elements into the HashSet during Iteration is not allowed. In such cases, java.util.ConcurrentModificationException will be raised.

How to iterate HashSet in java using forEach() method?

Since Java 8, a new method is added to the HashSet which is forEach() method and this method can be used to iterate HashSet in java. The forEach() method takes an argument of the Consumer Functional Interface. This consumer object is passed as an argument of the forEach() method and consumes each element of the HashSet one-by-one.
How to create an object of Consumer
Consumer<String> consumer = (String book) -> System.out.println(book);
Above, Lambda Expression is used to create an object of Consumer. If you don't know about what is a lambda expression, read this post: Lambda Expression in Java.
Let's look at the example to better understand:

Java HashSet Iterator Example 3: Iterate HashSet using forEach() method

// With Lambda Expression
bookSet.forEach((String book) -> System.out.println(book));
// Or, with Method Reference
bookSet.forEach(System.out::println);
Output
Programming In Java
Introduction to Algorithms
Data Structures
Learn C++
Computer Networks
Note: Similar to Iterators, Any Addition or Modification of the elements into the HashSet during Iteration is not allowed. In such cases java.util.ConcurrentModificationException will be raised.

Comments