Iterate over TreeSet in Java Example

Java TreeSet Examples


<__
The following example shows different ways of iterating over a TreeSet.
  • Iterate over a HashSet using Java 8 forEach and lambda expression.
  • Iterate over a HashSet using iterator().
  • Iterate over a HashSet using iterator() and Java 8 forEachRemaining() method.
  • Iterate over a HashSet using a simple for-each loop.

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 Java 8 forEach and lambda ===");
        fruits.forEach(fruit - > {
            System.out.println(fruit);
        });

        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);
        });

        System.out.println("=== Iterate over a HashSet using simple for-each loop ===");
        for (String fruit: fruits) {
            System.out.println(fruit);
        }
    }
}

Output

=== Iterate over a HashSet using Java 8 forEach and lambda ===
Apple
Banana
Orange
Pineapple
=== 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
=== Iterate over a HashSet using simple for-each loop ===
Apple
Banana
Orange
Pineapple

Reference



Comments