Iterate over LinkedHashSet using Iterator in Java Example

The following example shows how to iterating over a LinkedHashSet using Iterator:
  • Iterate over a HashSet using iterator().
  • Iterate over a HashSet using iterator() and Java 8 forEachRemaining() method.

Iterate over LinkedHashSet using Iterator in Java 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 iterator() ===");
        Iterator < String > programmingLanguageIterator = programmingLanguages.iterator();
        while (programmingLanguageIterator.hasNext()) {
            String programmingLanguage = programmingLanguageIterator.next();
            System.out.println(programmingLanguage);
        }

        System.out.println("=== Iterate over a LinkedHashSet using iterator() and Java 8 forEachRemaining() method ===");
        programmingLanguageIterator = programmingLanguages.iterator();
        programmingLanguageIterator.forEachRemaining(programmingLanguage - > {
            System.out.println(programmingLanguage);
        });
    }
}

Output

=== Iterate over a LinkedHashSet using iterator() ===
C
C++
Java
Python
PHP
Ruby
=== Iterate over a LinkedHashSet using iterator() and Java 8 forEachRemaining() method ===
C
C++
Java
Python
PHP
Ruby

Reference

https://www.javaguides.net/2018/06/guide-to-linkedhashset-class.html

Comments