Iterating over a TreeSet using Java 8 forEach() Method

Java TreeSet Examples


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

Iterating over a TreeSet using Java 8 forEach() Method

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 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 simple for-each loop ===
Apple
Banana
Orange
Pineapple

Reference




Comments