1. Introduction
The TreeSet class in Java provides a mechanism to store unique elements in a sorted order. Often, after storing data in a TreeSet, you’ll need to access and process each element. In this post, we will explore different methods to iterate over the elements of a TreeSet.
2. Program Steps
1. Create a TreeSet and add elements to it.
2. Iterate over the TreeSet using different methods:
a. Using an enhanced for-loop.
b. Using the forEach() method.
c. Using an iterator.
3. Code Program
import java.util.Iterator;
import java.util.TreeSet;
public class IterateOverTreeSet {
public static void main(String[] args) {
// Step 1: Create a TreeSet and add elements
TreeSet<String> fruits = new TreeSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
fruits.add("Date");
// 2a. Using enhanced for-loop
System.out.println("Using enhanced for-loop:");
for (String fruit : fruits) {
System.out.println(fruit);
}
// 2b. Using forEach method
System.out.println("\nUsing forEach method:");
fruits.forEach(fruit -> System.out.println(fruit));
// 2c. Using iterator
System.out.println("\nUsing iterator:");
Iterator<String> iterator = fruits.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
Output:
Using enhanced for-loop: Apple Banana Cherry Date Using forEach method: Apple Banana Cherry Date Using iterator: Apple Banana Cherry Date
4. Step By Step Explanation
Step 1: We initialize a TreeSet named fruits and populate it with a few fruit names.
Step 2a: We utilize an enhanced for-loop, also known as the "for-each" loop, to iterate over each element of the TreeSet. This method provides a concise way to loop over collections in Java.
Step 2b: The forEach() method is introduced in Java 8, offering another efficient and concise way to iterate over collections. It accepts a lambda expression and applies it to each element in the TreeSet.
Step 2c: The traditional way of iterating over collections is using an Iterator. The iterator provides methods like hasNext() to check if more elements are available and next() to access the next element.
All three methods produce the same output, displaying the names of fruits in the natural order. The choice of method largely depends on the use-case and developer's preference.