Java HashSet.iterator() – Examples

In this tutorial, we will learn about the Java HashSet.iterator() method, and learn how to use this method to get iterator for the elements in the HashSet, with the help of examples.

iterator()

HashSet.iterator() returns an iterator over the elements in this set.

Syntax

The syntax of iterator() method is

</>
Copy
HashSet.iterator()

Returns

This method returns Iterator<E> object. E is the type of elements in the HashSet.

Example 1 – iterator()

In this example, we will define a HashSet of Strings and add some elements to it. We shall then iterator to the elements in the HashSet using iterator() method.

Java Program

</>
Copy
import java.util.HashSet;
import java.util.Iterator;

public class Example {  
	public static void main(String[] args) {
		HashSet<String> hashSet = new HashSet<String>();
		hashSet.add("a");
		hashSet.add("b");
		hashSet.add("c");
		hashSet.add("d");

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

		while (iterator.hasNext()) { 
			System.out.println(iterator.next()); 
		}
	}  
}

Output

a
b
c
d

Example 2 – iterator() – User-defined Objects

In this example, we will define a HashSet of user defined type Car and add some elements to it. We shall then iterator to the elements in the HashSet using iterator() method.

Java Program

</>
Copy
import java.util.HashSet;
import java.util.Iterator;

public class Example {  
	public static void main(String[] args) {
		Car car1 = new Car(1, "Tesla");
		Car car2 = new Car(2, "BMW");
		Car car3 = new Car(3, "Toyota");
		
		HashSet<Car> hashSet = new HashSet<Car>();
		hashSet.add(car1);
		hashSet.add(car2);
		hashSet.add(car3);
		
		Iterator<Car> iterator = hashSet.iterator();
		
		while(iterator.hasNext()) {
			System.out.println(iterator.next());
		}
    }  
}

class Car {
	int id;
	String name;
	
	public Car(int id, String name) {
		this.id = id;
		this.name = name;
	}
	
	@Override
	public String toString() {
		return id + "-" + name;
	}
}

Output

1-Tesla
3-Toyota
2-BMW

Conclusion

In this Java Tutorial, we have learnt the syntax of Java HashSet.iterator() method, and also learnt how to use this method with the help of examples.