Treeset in Java

The TreeSet class in Java serves as an implementation of the Set interface and is backed by a TreeMap. It creates a collection that utilizes a tree data structure for efficient storage and retrieval of elements. Objects within a TreeSet are stored in sorted, ascending order based on their natural order.

One notable characteristic of the TreeSet implementation is its ability to automatically sort elements based on the lexicographic order of their string values. This default sorting behavior ensures that elements are arranged in a predictable and orderly manner. However, it is also possible to alter the natural order of a TreeSet by utilizing the Comparable or Comparator interfaces. By implementing these interfaces, custom sorting criteria can be defined, allowing for the arrangement of elements based on specific requirements.

Additionally, TreeSet guarantees that it contains unique elements, similar to the HashSet implementation. Duplicate elements are automatically eliminated, ensuring that each element within the TreeSet is distinct.

If you require a collection that maintains a sorted set of elements, TreeSet is the ideal choice. It provides efficient sorting capabilities along with the benefits of a Set, such as uniqueness and convenient methods for adding, removing, and accessing elements.

The following Java program illustrates several of the methods supported by this TreeSet collection Framework

import java.util.*; class TestClass { public static void main (String[] args) throws java.lang.Exception { //create a TreeSet Object TreeSet days=new TreeSet(); // add elements to the TreeSet days.add("Sunday"); days.add("Monday"); days.add("Tuesday"); days.add("Wednesday"); days.add("Thursday"); days.add("Friday"); days.add("Saturday"); //Iterate through TreeSet Iterator itr=days.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } //remove a single entry from TreeSet days.remove("Monday"); System.out.println(days); //search in TreeSet if(days.contains("Saturday")) System.out.println("Item Found"); else System.out.println("Item Not Found"); //Remove all items from TreeSet days.clear(); //Size of the TreeSet System.out.println("Size of the HashSet: "+days.size()); } }

Conclusion

TreeSet class in Java provides a versatile implementation of the Set interface, offering a collection that is both sorted and free of duplicate elements. It utilizes a TreeMap as its underlying data structure, allowing for efficient storage and retrieval of elements in ascending order according to their natural order or a specified Comparator.