TreeSet is an ordered and sorted set. It will give you the elements in the ascending order. It uses the Red-black tree structure. As of Java 6 specification, TreeSet Implements NavigableSet interface. There are four types of constructors of TreeSet:
- TreeSet( )
- TreeSet(Collection c)
- TreeSet(Comparator comp)
- TreeSet(SortedSet s)
The first constructor by default sorts the element by natural order. Second constructor takes the c as an argument and sorts the collection by natural order. Third takes the comp as an argument and sorts as per the Comparator. Fourth sorts the elements as provided by SortedSet.
Methods Of TreeSet
boolean add(element) – Adds the element to set.
boolean addAll(Collection c)– Adds all the element to the set specified in the collection
boolean contains(Object o)– Returns true if set contains specified element.
<E>first() – Returns the 1st element in the set.
<E>last() – Returns the last element in the set.
<E>ceiling(E e) – Returns the least element in the list greater than or equal to given element or null if not present any.
<E>floor(E e)– Returns the greatest element in the set less than or equal to the given element or null if not present any.
void clear() – Removes all the element from the set.
Object clone() – Returns a copy of the TreeSet instance.
boolean isEmpty() – Returns true if set contains no element.
Let see an example of TreeSet.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import java.util.*; public class TreeDemo { public static void main(String[] args) { TreeSet tr = new TreeSet(); tr.add(50); tr.add(30); tr.add(28); tr.add(35); tr.add(16); System.out.println("Elements of Tree are: " +tr); System.out.println("Number of elements in tree are "+tr.size()); System.out.println("Tree contains "+tr.ceiling(30)+ " is " tr.contains(30)); System.out.println("Tree's First element " +tr.first()); System.out.println("Tree's Last element " +tr.last()); tr.clear(); if (tr.isEmpty()) { System.out.println("Tree is empty"); } else { System.out.println(tr.size()); } } } |
Output:
Elements of Tree are: [16, 28, 30, 35, 50]
Number of elements in tree are 5
Tree contains 30 is true
Tree’s First element 16
Tree’s Last element 50
Tree is empty
Iterating through TreeSet
Let see an example iterating through TreeSet
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.util.*; public class TreeDemo { public static void main(String[] args) { TreeSet<Integer> tr = new</strong> TreeSet<Integer>(); tr.add(50); tr.add(30); tr.add(28); tr.add(35); tr.add(16); System.out.println("Elements of Tree are: " +tr); System.out.println("Number of elements in tree are "+tr.size()); Iterator<Integer> it = tr.iterator(); while(it.hasNext()) { System.out.print(it.next()+ " "); } } } |
Output:
Elements of Tree are: [16, 28, 30, 35, 50]
Number of elements in tree are 5
16 28 30 35 50
Leave a Reply