Different Ways to Iterate over a Set in Java

Iterate over a Set

A Set is a Collection that cares about uniqueness, it doesn’t allow duplicate elements. The .equals() method determines whether two objects are identical in witch case only one object can be in the set.

package com.memorynotfound.collections.set;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

 * @author MemoryNotFound.com
public class SetIterateProgram {

    public static void main(String... args){

        Set<String> cars = new HashSet<String>();
        cars.add("DeLorean DMC-12 1982");
        cars.add("corvette stingray 1960");
        cars.add("mustang fastback 1967");

        // Enhanced for loop
        for (String car : cars){

        // Basic loop with iterator
        for(Iterator<String> it = cars.iterator();it.hasNext();)  {

        // While loop with iterator
        Iterator<String> it = cars.iterator();
            String car = it.next();

        // JDK 8 streaming example lambda expression
        cars.stream().forEach(color -> carPrinter(color));

        // JDK 8 streaming example method reference

        // JDK 8 for each with lambda
        cars.forEach(color -> carPrinter(color));

        // JDK 8 for each


    private static void carPrinter(String car){

note: If you want to use the JDK 8 way (lambda expression, method reference) you of course need to use the new JDK-8 in your project.

Sample output

Because a hashSet is not an ordered list, the order of the output may vary.

corvette stingray 1960
mustang fastback 1967
DeLorean DMC-12 1982

You may also like...