Iterate over a TreeSet using Iterator in Java Example

Java TreeSet Examples


<__
The following example shows how to iterate over a TreeSet using Iterator.
  • Iterate over a HashSet using iterator().
  • Iterate over a HashSet using iterator() and Java 8 forEachRemaining() method.

Different ways of iterating over a TreeSet

package com.javaguides.collections.treesetexamples;

import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;

public class IterateOverTreeSetExample {
    public static void main(String[] args) {
        // Creating a TreeSet
        SortedSet < String > fruits = new TreeSet < > ();

        // Adding new elements to a TreeSet
        fruits.add("Banana");
        fruits.add("Apple");
        fruits.add("Pineapple");
        fruits.add("Orange");

        System.out.println("=== Iterate over a HashSet using iterator() ===");
        Iterator < String > fruitIterator = fruits.iterator();
        while (fruitIterator.hasNext()) {
            String fruit = fruitIterator.next();
            System.out.println(fruit);
        }

        System.out.println("=== Iterate over a HashSet using iterator() and Java 8 forEachRemaining() method ===");
        fruitIterator = fruits.iterator();
        fruitIterator.forEachRemaining(fruit - > {
            System.out.println(fruit);
        });
    }
}

Output

=== Iterate over a HashSet using iterator() ===
Apple
Banana
Orange
Pineapple
=== Iterate over a HashSet using iterator() and Java 8 forEachRemaining() method ===
Apple
Banana
Orange
Pineapple

Reference



Comments