import java.util.*;
class TreeSet_TechSarvam
{
public static void main(String args[])
{
// Creating and adding elements to TreeSet
TreeSet<String> al = new TreeSet<String>();
al.add("Rajendra");
al.add("Raja");
al.add("Ravi");
al.add("TechSarvam");
// Traversing elements using Iterator
Iterator<String> itr = al.iterator();
while (itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Step-by-Step Explanation:
1. Importing Required Classes:
import java.util.*;
This line imports necessary classes from the java.util package. It is required to use classes like TreeSet and Iterator.
2. Class Declaration:
class TreeSet_TechSarvam {
The class TreeSet_TechSarvam defines that holds the method main() and holds all the programmatic logics.
3. Main Method:
public static void main(String args[]) {
It’s where your program actually gets to work: that’s a method that Java has created.
4. Creating a TreeSet: TreeSet <String> al = new TreeSet <String>();
- A TreeSet is declared and assigned to the variable al. The TreeSet class implements the Set interface, and it stores elements in a sorted order.
- The type of elements in the TreeSet is specified as String (so the set will only contain strings).
5. Adding Elements to the TreeSet:
al.add(“Rajendra”);
al.add(“Raja”);
al.add(“Ravi”);
al.add(“TechSarvam”);
- The add() method has been used to add elements to the TreeSet. The elements added are “Rajendra”, “Raja”, “Ravi”, and “TechSarvam”.
- A TreeSet will automatically sort the elements it holds in ascending order (based on their natural ordering or a Comparator supplied at creation time).
- The elements are not kept in the insertion order. “Rajendra”, “Raja”, “Ravi”, and “TechSarvam” will be arranged alphabetically.
6. Creation of an Iterator for Traversal:
Iterator<String> itr = al.iterator();
An Iterator is obtained to iterate over the TreeSet. The iterator() method of the TreeSet is invoked to get an Iterator.
7. Iterate over TreeSet:
while (itr.hasNext()) {
System.out.println(itr.next());
}
- The while loop checks for existence of elements in the TreeSet by itr.hasNext() If there are more elements then the loop continues.
- The itr.next() fetches the next element from the TreeSet and System.out.println prints to the console.
- As TreeSet stores the elements in the sorted order so, while running the loop it will print them in ascending order.
Expected Output:
As it is a sorted set, that is, TreeMap automatically sorts elements in ascending order, so will print them alphabetically:
——————————————————–
Rajendra
Raja
Ravi
TechSarvam