Menu
Topics Index
...
`


Collections Framework > Collection Classes >
Siva Nookala - 06 Oct 2016
TreeSet is one of two sorted collections the other is TreeMap In Java - java.util.TreeMap. TreeSet extends AbstractSet and implements the Java NavigableSet Interface . It creates a collection that uses a tree for storage. Objects are stored in sorted, ascending order according to natural order. Optionally, we can change the natural order of a TreeSet by using a Comparable or Comparator interfaces.

Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing large amounts of sorted information that must be found quickly. TreeSet might not be used when our application has requirement of modification of set in terms of frequent addition of elements.
Below shown is the hierarchy of the TreeSet.
java.lang.Object

        java.util.AbstractCollection

                java.util.AbstractSet

                        java.util.TreeSet

Constructors of TreeSet :
Constructor Description
TreeSet() Constructs a new, empty tree set, sorted according to the natural ordering of its elements.
TreeSet(Collection<? extends E> c) Constructs a new tree set containing the elements in the specified collection, sorted according to the natural ordering of its elements.
TreeSet(Comparator<? super E> comparator) Constructs a new, empty tree set, sorted according to the specified comparator
TreeSet(SortedSet<E> s) Constructs a new tree set containing the same elements and using the same ordering as the specified sorted set.
Apart from the methods inherited from its parent classes, TreeSet defines the following methods:
Method Description
void add(Object o) Adds the specified element to this set if it is not already present.
boolean addAll(Collection c) Adds all of the elements in the specified collection to this set.
void clear() Removes all of the elements from this set.
Object clone() Returns a shallow copy of this TreeSet instance.
Comparator comparator() Returns the comparator used to order this sorted set, or null if this tree set uses its elements natural ordering.
boolean contains(Object o) Returns true if this set contains the specified element.
Object first() Returns the first (lowest) element currently in this sorted set.
SortedSet headSet(Object toElement) Returns a view of the portion of this set whose elements are strictly less than toElement.
boolean isEmpty() Returns true if this set contains no elements.
Iterator iterator() Returns an iterator over the elements in this set.
Object last() Returns the last (highest) element currently in this sorted set.
boolean remove(Object o) Removes the specified element from this set if it is present.
int size() Returns the number of elements in this set (its cardinality).
SortedSet subSet(Object fromElement, Object toElement) Returns a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive.
SortedSet tailSet(Object fromElement) Returns a view of the portion of this set whose elements are greater than or equal to fromElement.
TreeSetSample
import java.util.*;

class TreeSetSample
{
    public static void main(String arg[])
    {
        TreeSet<Integer> input = new TreeSet<Integer>(); // LINE A
        input.add(1);
        input.add(3);
        input.add(2);
        input.add(6);
        input.add(5);
        input.add(4);
        System.out.println(input); // LINE B
        System.out.println("First Element in Set : " + input.first()); // LINE C
        System.out.println("Last Element in Set : " + input.last()); // LINE D
        System.out.println("Element higher to 4 : " + input.higher(4)); // LINE E
        //higher returns the next higher number to the given number
        System.out.println("Element lower to 3 : " + input.lower(3));
        //lower returns the next lower number to the given number    
    }
}
OUTPUT

[1, 2, 3, 4, 5, 6]
First Element in Set : 1
Last Element in Set : 6
Element higher to 4 : 5
Element lower to 3 : 2

DESCRIPTION

In the above program we demonstrated how TreeSet functions at LINE A we have created an empty TreeSet and added elements to it. At LINE B we are displaying the sorted elements of TreeSet. At LINE C we are getting the first element of the Set using first method. At LINE D we are getting last element of the Set using last method. At LINE E we are displaying the next higher number of 4 in the Set using higher method and at LINE F we are displaying the next lower number of 3 in the Set using lower method.

THINGS TO TRY
  • Now try to get a subset of the above shown set from index 0 to index 4. Use the below sample code.
    TreeSet set = input.subSet(0, 4);
    System.out.println(set);
  • Display the elements which are less than 5 using headSet method. Use the below sample code.
    System.out.println(input.headSet(5));
    The output will be [1, 2, 3, 4] Since the return type of the headSet is SortedSet.
  • Display the elements which are greater than or equal to 2 using tailSet method. Use the below sample code._
    System.out.println(input.tailSet(2));
    The output will be [2, 3, 4, 5, 6]. Since the tailSet method returns a portion of the set whose elements are greater than or equal to given element.
Now lets see a program to sort the objects using a Comparable interface.
TreeSetCustomSortingDemo
import java.util.*;

class TreeSetCustomSortingDemo
{
    public static void main(String arg[])
    {
        TreeSet<Student> students = new TreeSet<Student>(); // LINE B
        students.add(new Student("Sreeram", 10, 'A'));
        students.add(new Student("Karthik", 12, 'A'));
        students.add(new Student("Ram", 14, 'B'));
        students.add(new Student("Yeshwanthi", 5, 'C'));
        students.add(new Student("Bhavya", 6, 'D'));
        System.out.println(students); // LINE C
        TreeSet newStudents = (TreeSet) students.clone();
    
    }
}

class Student implements Comparable<Student>
{
    String name;
    int rollNumber;
    char section;
    
    public Student(String name, int rollNumber, char section)
    {
        this.name = name;
        this.rollNumber = rollNumber;
        this.section = section;
    }
    
    public String toString()
    {
        return name + " " + rollNumber + " " + section;
    }
    
    public int compareTo(Student o)
    {
        return rollNumber - o.rollNumber;
    }
}
OUTPUT

[Yeshwanthi 5 C, Bhavya 6 D, Sreeram 10 A, Karthik 12 A, Ram 14 B]

DESCRIPTION

In the above program we have demonstrated how to change the natural ordering of the TreeSet depending on the requirements. Firstly we have created a Student class which implements Comparable interface with the fields name, rollNumber, section and implemented toString and compareTo method of Comparable interface. At LINE B in the other class we have created a TreeSet and added Student objects. Now Set will consider the compareTo method in the Student class and sorts the objects accordingly.

THINGS TO TRY
  • Now sort the elements with respect to section. Use the below sample code.
    return rollNumber - o.rollNumber;
  • Create a clone for the above set using clone method. Use the below sample code.
    TreeSet newStudents = (TreeSet) students.clone();
    In the above code we type casted to TreeSet since the return type of clone is Object a Type mismatch exception may raise otherwise.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.