Languages
[Edit]
EN

Java - different ways of how to iterate over Set or HashSet

14 points
Created by:
Marcin
15740

1. Overview

In java we can traverse over Set or HashSet with different ways.

Old ways involve Iterator, with java 8 we can use stream / forEach.

There is also an ancient way with Enumeration.

Below we can see 7 different ways of how to iterate over Set in java.

2. Code example

import java.util.*;

public class JavaIterateOverHashSet {

    public static void main(String[] args) {

        Set<String> set = new HashSet<>();
        set.add("A");
        set.add("B");
        set.add("C");

        System.out.println("#1");
        for (String s : set) {
            System.out.print(s + ", ");
        }

        System.out.println("\n#2"); // java 8
        set.forEach(s -> {
            System.out.print(s + ", ");
        });

        System.out.println("\n#3"); // java 8
        set.forEach(s -> System.out.print(s + ", "));

        System.out.println("\n#4");  // java 8
        set.forEach(System.out::print);

        System.out.println("\n#5");  // java 8
        set.stream().forEach(System.out::print);

        System.out.println("\n#6");
        Iterator<String> itr = set.iterator();
        while (itr.hasNext()) {
            System.out.print(itr.next() + ", ");
        }

        System.out.println("\n#7");
        Enumeration elements = new Vector(set).elements();
        while (elements.hasMoreElements()) {
            System.out.print(elements.nextElement() + ", ");
        }
    }
}

Output:

#1
A, B, C, 
#2
A, B, C, 
#3
A, B, C, 
#4
ABC
#5
ABC
#6
A, B, C, 
#7
A, B, C, 

 

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join