TreeSet Example Add, Print, Extract Elements

    Two Programs exists on TreeSet.

    1. TreeSet General: General operations like printing the elements in natural order (the default behavior of SortedSet, the super class of TreeSet), extracting a part of a set, creating generics TreeSet etc. are performed.
    2. TreeSet Special: Operations like cloning the TreeSet, iterating elements with Iterator and the methods like retainAll(), addAll(), containsAll(), size(), remove(), clear() and equals() are performed. The operations are done on a generics TreeSet that stores strings.

    This is the first TreeSet Example of the above two.

    Note: It is advised to read before going through this program, TreeSet Tutorial, to get acquainted with the methods and features of TreeSet.

    import java.util.*;
    public class TreeSetGeneral
      public static void main(String args[])
        TreeSet ts1 = new TreeSet();
        System.out.println("All the elements of ts1: " + ts1);
        System.out.println("First element of ts1: " + ts1.first());
        System.out.println("Last element of ts1: " + ts1.last());
        SortedSet ts2 = ts1.subSet(20, 40);
        System.out.println("\nSub set ts2 elements: " + ts2);
        SortedSet ts3 = ts1.tailSet(30);
        System.out.println("Tail set ts3 elements: " + ts3);

    TreeSet ts1 = new TreeSet();

    A generics TreeSet ts1 is created that stores only integer values. With add() method five elements are added.

    System.out.println(“All the elements of ts1: ” + ts1);

    Just printing the elements of TreeSet ts1, prints the elements in ascending order (known as natural order).

    System.out.println(“First element of ts1: ” + ts1.first());
    System.out.println(“Last element of ts1: ” + ts1.last());

    The first() and last() methods, inherited from SortedSet interface, return the first element and last elements of the TreeSet ts1.

    SortedSet ts2 = ts1.subSet(20, 40);

    The subSet(20, 40) method, inherited from SortedSet, returns all the elements having value from 20 and below 40.

    SortedSet ts3 = ts1.tailSet(30);

    The tailSet(30) method, inherited from SortedSet, returns all the elements having value 30 and greater than 30.

    Pass your comments on this tutorial TreeSet Example

1 thought on “TreeSet Example Add, Print, Extract Elements”

Leave a Comment

Your email address will not be published.