1. Introduction
In Java, TreeSet is a NavigableSet implementation that stores elements in a sorted order. Iterating over a TreeSet allows us to access its elements in ascending order. In this blog post, we will explore different ways to iterate over a TreeSet in Java.
2. Program Steps
1. Create a TreeSet and add elements to it.
2. Iterate over the TreeSet using the enhanced for loop.
3. Iterate over the TreeSet using the iterator method.
4. Iterate over the TreeSet using a lambda expression and the forEach method.
3. Code Program
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetIteration {
public static void main(String[] args) {
// Step 1: Create a TreeSet and add elements to it
TreeSet<String> treeSet = new TreeSet<>();
treeSet.add("Apple");
treeSet.add("Banana");
treeSet.add("Cherry");
// Step 2: Iterate over the TreeSet using the enhanced for loop
System.out.println("Using enhanced for loop:");
for(String fruit : treeSet) {
System.out.println(fruit);
}
// Step 3: Iterate over the TreeSet using the iterator method
System.out.println("\nUsing iterator:");
Iterator<String> iterator = treeSet.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
// Step 4: Iterate over the TreeSet using lambda expression and forEach method
System.out.println("\nUsing forEach and lambda expression:");
treeSet.forEach(fruit -> System.out.println(fruit));
}
}
Output:
Using enhanced for loop: Apple Banana Cherry Using iterator: Apple Banana Cherry Using forEach and lambda expression: Apple Banana Cherry
4. Step By Step Explanation
Step 1: We create a TreeSet and add three elements "Apple", "Banana", and "Cherry" to it.
Step 2: We iterate over the TreeSet using the enhanced for loop and print each element. The enhanced for loop is a simpler way to iterate over collections, and it is read-only.
Step 3: We use the iterator method to get an Iterator for the TreeSet and then iterate over the elements using the hasNext and next methods of the Iterator. This approach gives more control compared to the enhanced for loop, such as the ability to remove elements during iteration.
Step 4: We use the forEach method along with a lambda expression to iterate over the TreeSet. This method is a functional approach introduced in Java 8, which is concise and provides better readability.