Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to use TreeSet in Java with example ?.

Program to demonstrate how to implement TreeSet class in java.util.*; package along with its operations :

package com.hubberspot.collections.example;

import java.util.*;

public class TreeSetExample
{
  public static void main(String[] args)
{
    TreeSet treeSet = new TreeSet();
    
    treeSet.add("d");
    treeSet.add("a");
    treeSet.add("s");
    treeSet.add("f");
    treeSet.add("k");
    
    System.out.println("The contents of set : "
       + treeSet);  

    System.out.println("The size of set : "
       + treeSet.size());
    
    SortedSet sortedSet = treeSet.headSet("d");

    System.out.println("The elements < d are : "
       + sortedSet);

    sortedSet = treeSet.tailSet("d");

    System.out.println("The elements > d are : "
       + sortedSet);

    sortedSet = treeSet.subSet("c", "s");

    System.out.println("The elements > d are : "
       + sortedSet);
    
 } 
}

Output of the program :


 
© 2021 Learn Java by Examples Template by Hubberspot