Iterating over a LinkedHashSet using forEach() Method Example

The following example shows how to Iterate over a LinkedHashSet using forEach() Method Example.
  • Iterate over a HashSet using Java 8 forEach and lambda expression.
  • Iterate over a HashSet using a simple for-each loop.

Iterating over a LinkedHashSet using forEach() Method Example

package com.javaguides.collections.linkedhashsetexamples;

import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;

public class IterateOverLinkedHashSetExample {
    public static void main(String[] args) {
        Set < String > programmingLanguages = new LinkedHashSet < > ();
        programmingLanguages.add("C");
        programmingLanguages.add("C++");
        programmingLanguages.add("Java");
        programmingLanguages.add("Python");
        programmingLanguages.add("PHP");
        programmingLanguages.add("Ruby");

        System.out.println("=== Iterate over a LinkedHashSet using Java 8 forEach and lambda ===");
        programmingLanguages.forEach(programmingLanguage - > {
            System.out.println(programmingLanguage);
        });

        System.out.println("=== Iterate over a LinkedHashSet using simple for-each loop ===");
        for (String programmingLanguage: programmingLanguages) {
            System.out.println(programmingLanguage);
        }
    }
}

Output

=== Iterate over a LinkedHashSet using Java 8 forEach and lambda ===
C
C++
Java
Python
PHP
Ruby
=== Iterate over a LinkedHashSet using simple for-each loop ===
C
C++
Java
Python
PHP
Ruby

Reference

Comments