TreeSet in Java

Introduction

The TreeSet in Java is one of the most used instances of the SortedSet interface. The Tree Set is sorted in the natural order of the elements (alphabetically or numerically depending on the type of elements) if not specified otherwise with a comparator. The TreeSet implements a NavigableSet interface by inheriting the AbstractSet class. It is part of the java.util package under the Collections framework.

Declaration Syntax

public class TreeSet <E> extends AbstractSet <E> implements NavigableSet <E>, Cloneable, Serializable.

How to Create a Simple TreeSet

import java.util.*;
class TreeSetExample
{
public static void main(String[] args)
{
TreeSet<String> ts1 = new TreeSet<String>();

ts1.add("A");
ts1.add("B");
ts1.add("C");

ts1.add("C");

System.out.println(ts1);
}
}

 

OUTPUT

[A, B, C]

Adding Elements to a TreeSet

import java.util.*;
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet<String> ts = new TreeSet<String>();

ts.add("Hello");
ts.add("World");
ts.add("Program");
System.out.println(ts);
}
}

OUTPUT

[Hello, World, Program]

Accessing Elements

import java.util.*;
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet<String> ts = new TreeSet<String>();

ts.add("Hello");
ts.add("World");
ts.add("Program");
System.out.println("Tree Set is " + ts);
String check = "Hello";

//Will Check if the String Hello is contained in the program. Will return true if present
System.out.println("Contains " + check + " " + ts.contains(check));

//first() method is used to get the first element of the Tree Set
System.out.println("First Value " + ts.first());

//last() method is used to get the last element of the Tree Set
System.out.println("Last Value " + ts.last());

String val = "Hello";

//higher() and lower() methods are used to find the immediate higher and lower values of the //reference string. If there is no higher or lower value, the referenced string will be returned.
System.out.println("Higher " + ts.higher(val));
System.out.println("Lower " + ts.lower(val));
}
}

OUTPUT

Tree Set is [Hello, World, Program] Contains Hello true
First Value Hello
Last Value World
Higher Hello
Lower Program

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.