Treeset in Java

How to Java Treeset TreeSet class implements the Set interface, backed by a TreeMap . It creates a collection that uses a tree for storage. Objects are stored in sorted, ascending order according to natural order. The TreeSet implementation is sorting by the lexicographic order of the string values you insert. Optionally, we can change the natural order of a TreeSet by using a Comparable or Comparator interfaces. Moreover, it contains unique elements only like HashSet. If you need a sorted set, then TreeSet should be used. TreeSet might not be used when our application has requirement of modification of set in terms of frequent addition of elements. Because this implementation is not synchronized. If multiple threads access a TreeSet concurrently, and at least one of the threads modifies the TreeSet, it must be synchronized externally.

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(; } //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()); } }