How to Iterate over a Set/HashSet without an Iterator? – Dev

The best answers to the question “How to Iterate over a Set/HashSet without an Iterator?” in the category Dev.


How can I iterate over a Set/HashSet without the following?

Iterator iter = set.iterator();
while (iter.hasNext()) {


There are at least six additional ways to iterate over a set. The following are known to me:

Method 1

// Obsolete Collection
Enumeration e = new Vector(movies).elements();
while (e.hasMoreElements()) {

Method 2

for (String movie : movies) {

Method 3

String[] movieArray = movies.toArray(new String[movies.size()]);
for (int i = 0; i < movieArray.length; i++) {

Method 4

// Supported in Java 8 and above -> {

Method 5

// Supported in Java 8 and above -> System.out.println(movie));

Method 6

// Supported in Java 8 and above;

This is the HashSet which I used for my examples:

Set<String> movies = new HashSet<>();
movies.add("The Lord of the Rings");


You can use an enhanced for loop:

Set<String> set = new HashSet<String>();

//populate set

for (String s : set) {

Or with Java 8:



To demonstrate, consider the following set, which holds different Person objects:

Set<Person> people = new HashSet<Person>();
people.add(new Person("Tharindu", 10));
people.add(new Person("Martin", 20));
people.add(new Person("Fowler", 30));

Person Model Class

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) { = name;
        this.age = age;

    //TODO - getters,setters ,overridden toString & compareTo methods

  1. The for statement has a form designed for iteration through Collections and arrays .This form is sometimes referred to as the enhanced for statement, and can be used to make your loops more compact and easy to read.
for(Person p:people){
  1. Java 8 – java.lang.Iterable.forEach(Consumer)
people.forEach(p -> System.out.println(p.getName()));
default void forEach(Consumer<? super T> action)

Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. Unless otherwise specified by the implementing class, actions are performed in the order of iteration (if an iteration order is specified). Exceptions thrown by the action are relayed to the caller. Implementation Requirements:

The default implementation behaves as if: 

for (T t : this)

Parameters: action - The action to be performed for each element

Throws: NullPointerException - if the specified action is null

Since: 1.8


Converting your set into an array
may also help you for iterating over the elements:

Object[] array = set.toArray();

for(int i=0; i<array.length; i++)
   Object o = array[i];