A TreeSet in Java is an implementation of the SortedSet interface, which uses a Red-Black tree structure to store elements in sorted order. The sorting is based on either the natural ordering of elements or a custom comparator provided at the time of TreeSet creation. This makes TreeSet suitable for scenarios where you need elements to be ordered automatically.
import java.util.TreeSet;
// Syntax for creating a TreeSet with natural ordering
TreeSet<Type> setName = new TreeSet<>();
Code language: JavaScript (javascript)
import java.util.TreeSet; public class TreeSetExample { public static void main(String[] args) { // Creating a TreeSet to store student names TreeSet<String> studentSet = new TreeSet<>(); // Adding students to the TreeSet studentSet.add("Paani"); studentSet.add("Mahesh"); studentSet.add("Datta"); studentSet.add("Ganesh"); studentSet.add("Harsha"); // Attempting to add a duplicate student (Mahesh) boolean addedDuplicate = studentSet.add("Mahesh"); System.out.println("Duplicate 'Mahesh' added? " + addedDuplicate); // Displaying the set of students System.out.println("\nSet of students (sorted alphabetically):"); for (String student : studentSet) { System.out.println(student); } // Removing a student from the set studentSet.remove("Datta"); // Displaying the updated set System.out.println("\nUpdated set of students:"); for (String student : studentSet) { System.out.println(student); } // Checking if the set contains a student String searchStudent = "Harsha"; boolean containsStudent = studentSet.contains(searchStudent); System.out.println("\nDoes the set contain '" + searchStudent + "'? " + containsStudent); // Size of the set System.out.println("Size of the set: " + studentSet.size()); // Clearing the set studentSet.clear(); System.out.println("Is the set empty now? " + studentSet.isEmpty()); } }
D:\>javac TreeSetExample.java
D:\>java TreeSetExample
Duplicate 'Mahesh' added? false
Set of students (sorted alphabetically):
Datta
Ganesh
Harsha
Mahesh
Paani
Updated set of students:
Ganesh
Harsha
Mahesh
Paani
Does the set contain 'Harsha'? true
Size of the set: 4
Is the set empty now? true
Code language: JavaScript (javascript)
TreeSet in Java provides a sorted collection of unique elements, offering automatic ordering based on natural order or custom comparators. It is useful in scenarios where you need elements to be automatically sorted and unique. Understanding its features and usage allows developers to design efficient and organized data structures in Java applications.