TreeSet Example Java Program


Definition

TreeSet uses a red-black tree implemented by a java.util.TreeMap. The red-black tree makes sure that there are no duplicates. Additionally, it allows TreeSet to implement java.util.SortedSet. Thus TreeSet itself sorts the values in it.

Syntax

TreeSet<variable-type> variableName = new TreeSet<variable-type>();

TreeSet Example Program

import java.util.Scanner;
import java.util.TreeSet;

public class TreeSetExample {

    public static void main(String[] args) {
        TreeSet<String> treeSet = new TreeSet<String>();
        System.out.println("Enter the input Strings to be added in TreeSet");
        Scanner input = new Scanner(System.in);
        String s1 = input.nextLine();
        String s2 = input.nextLine();
        String s3 = input.nextLine();
        String s4 = input.nextLine();
        treeSet.add(s1);
        treeSet.add(s2);
        treeSet.add(s3);
        treeSet.add(s4);
        System.out.println("TreeSet is : " + treeSet);
        System.out.println("Check if TreeSet is empty : " + treeSet.isEmpty());
        treeSet.remove(s2);
        System.out.println("After removing element : " + s2 + " TreeSet is : " + treeSet);
    }
}

Sample Output

Enter the input Strings to be added in TreeSet
zoooooo
yoooooo
xoooooo
woooooo
TreeSet is : [woooooo, xoooooo, yoooooo, zoooooo]
Check if TreeSet is empty : false
After removing element : yoooooo TreeSet is : [woooooo, xoooooo, zoooooo]