Tree Set:
- It is one of the two sorted collections.
- Uses the “Read-Black” tree structure and guarantees that the elements will be in ascending order.
- We can construct a tree set with the constructor by using a comparable (or) comparator.
Example:
public class Fruits{
public static void main (String[ ]args) {
Treeset<String> names= new TreeSet<String>( ) ;
names.add(“cherry”);
names.add(“banana”);
names.add(“apple”);
names.add(“kiwi”);
names.add(“cherry”);
System.out.println(names);
}
}
Output:
[apple, banana, cherry, kiwi]
TreeSet sorts the elements in ascending order. And duplicates are not allowed.