Core Java

Treeset Class Java Example

1. Introduction

In this article, we will take a look at the Treeset class in Java using examples. TreeSet implements the SortedSet interface in Java which persists in a Tree. The ordering of the elements in a TreeSet is based on natural ordering.

2. TreeSet Java Example

TreeSet does not allow duplicate values. TreeSet persists the objects sorted in ascending order. It does not maintain the order the way the elements are inserted. The elements in the Treeset are sorted by the keys. TreeSet allows the insertion of homogeneous objects. TreeSet throws ClassCastException when you try to insert heterogeneous objects.It is a good choice for persisting sorted information. TreeSet provides quicker access and finds the elements in a short time. It is the implementation of a self-balancing binary search tree such as Red-Black Tree. The tree operations such as add, remove and search execute in O(Log m) time. Printing m elements in sorted order gets executed in O(m) time.

2.1 Prerequisites

Java 8 is required on the Linux, Windows or Mac operating system. Eclipse Oxygen can be used for this example.

2.2 Download

You can download Java 8 from the Oracle web site . Eclipse Oxygen can be downloaded from the eclipse web site.

2.3 Setup

2.3.1 Java Setup

Below are the setup commands required for the Java Environment.

Setup

JAVA_HOME=”/jboss/jdk1.8.0_73″
export JAVA_HOME
PATH=$JAVA_HOME/bin:$PATH
export PATH

2.4 IDE

2.4.1 Eclipse Oxygen Setup

The ‘eclipse-java-oxygen-2-macosx-cocoa-x86_64.tar’ can be downloaded from the eclipse website. The tar file is opened by double click. The tar file is unzipped by using the archive utility. After unzipping, you will find the eclipse icon in the folder. You can move the eclipse icon from the folder to applications by dragging the icon.

2.4.2 Launching IDE

Eclipse has features related to language support, customization, and extension. You can click on the eclipse icon to launch eclipse. The eclipse screen pops up as shown in the screenshot below:

treeset java - Launching IDE
Launching IDE

You can select the workspace from the screen which pops up. The attached image shows how it can be selected.

treeset java - IntelliJ vs Eclipse
Eclipse Workspace

You can see the eclipse workbench on the screen. The attached screenshot shows the Eclipse project screen.

treeset java - Eclipse Workbench
Eclipse Workbench

Java Hello World class prints the greetings. The screenshot below is added to show the class and execution on the eclipse.

treeset java - Java Hello
Java Hello

2.5 What is a TreeSet?

Java TreeSet implements the NavigableSet interface which extends SortedSet, Set, Collection and Iterable interfaces in the order of hierarchy. Java TreeSet can store unique elements similar to HashSet. It can find and retrieve the element in a short time. TreeSet does not allow null objects. It is non-synchronized.

2.6 Treeset Constructors

TreeSet‘s constructor without parameter is used to create the instance as shown in the example below.

TreeSet Constructor without param

Set treeSetInstance = new TreeSet();

TreeSet‘s constructor with parameter Comparable or Comparator is used to create the instance which can sort based on Comparator or Comparable as shown in the below example.

TreeSet Constructor with param Comparator

Set treeSetInstance = new TreeSet(Comparator.comparing(String::length));

TreeSet‘s constructor with parameter Collection is used to convert the Collection to a TreeSet as shown in the code snippet below.

TreeSet Constructor with param Collection

TreeSet treeSetInstance = new TreeSet(Collection collection);

TreeSet‘s constructor with parameter Sorted Set is used to convert SortedSet object to TreeSet in the code sample below.

TreeSet Constructor with parameter SortedSet

TreeSet treeSetInstance = new TreeSet(SortedSet sortedSet);

2.7 Examples of using TreeSet

Let us now look at the example of using TreeSet for adding elements and printing the elements in the TreeSet.

TreeSet Constructor with param

import java.util.TreeSet; 

class TreeSetUsage { 
	public static void main(String[] args) 
	{ 
		TreeSet treeSetInstance = new TreeSet(); 

		treeSetInstance.add("element1"); 
        treeSetInstance.add("element2"); 
        treeSetInstance.add("element3"); 


        treeSetInstance.add("element2"); 
	
	Iterator iterator= treeSetInstance.descendingIterator();  
        while(iterator.hasNext())  
        {  
            System.out.println(iterator.next());  
        } 
	} 
}

The output of the above code example when executed is shown in the screenshot below.

treeset java - Usage
TreeSet Usage

Now let us look at the example where we see the Treeset with Integer Elements.

TreeSet with Integer Elements

import java.util.TreeSet; 

public class TreeSetTraverser { 
	public static void main(String[] args) 
	{ 
		TreeSet treeSetInstance = new TreeSet(); 

		treeSetInstance.add(1); 
        treeSetInstance.add(2); 
        treeSetInstance.add(3); 

        System.out.println("Highest Integer is "+ treeSetInstance.pollFirst());  
        System.out.println("Lowest Integer is "+ treeSetInstance.pollLast());
	} 
}

The output of the above code example when executed is shown in the screenshot below.

TreeSet Traverser

Let us look at TreeSet Example with Employee elements. Employee class has attributes id and name.

TreeSet with Employee Elements

import java.util.TreeSet;
import java.util.Set;

class Employee implements Comparable{  
      int id;  
     String name;  
 Employee(int id, String name) {  
    this.id = id;  
    this.name = name;  
  
}  
public int compareTo(Employee emp) {  
    if(id>emp.id){  
        return 1;  
    }else if(id<emp.id){  
        return -1;  
    }else{  
    return 0;  
    }  
}  
}  
public class TreeSetExample {  
public static void main(String[] args) {  
    Set employeeSet=new TreeSet();  
      
    Employee emp1=new Employee(1,"John Smith");  
    Employee emp2= new Employee(2,"William Brady");  
    Employee emp3= new Employee(3,"George Smith");  
      
    employeeSet.add(emp1);  
    employeeSet.add(emp2);
    employeeSet.add(emp3);
    
    for(Employee emp:employeeSet){  
        System.out.println(emp.id+" "+emp.name);  
    }  
}  
}

The output of the above code example when executed is shown in the screenshot below.

TreeSet Example with Employee

2.8 Choosing Treeset Instead of Other Data Structure

TreeSet is selected when the developer wants to preserve the order of elements of storage. The elements can be sorted alphabetically if the object representation is String or TreeSet is of the Generic type String. HashSet can be used if there is no sorting of the elements. It is also used if you want to store unique elements. TreeSet maintains the natural order and HashSet is used if there is no ordering of the elements.

2.9 Complexity of Operations

The TreeSet operations such as add, remove and search execute in O(Log m) time. Printing m elements in sorted order gets executed in O(m) time. Let us look at the example which shows to measure the execution time for different TreeSet operations.

TreeSet Performance

import java.util.TreeSet;

import java.util.Random;

import java.util.Iterator;

public class TreeSetPerformance {

	public static void main(String[] args) {
		Random rand = new Random();

		TreeSet treeSetInstance = new TreeSet();

		long startTime = System.nanoTime();
		treeSetInstance.add("Element1");
		long endTime = System.nanoTime();
		long duration = endTime - startTime;
		System.out.println("TreeSet adding time " + duration +" nano seconds");

		startTime = System.nanoTime();
		treeSetInstance.remove("Element1");
		endTime = System.nanoTime();
		duration = endTime - startTime;
		System.out.println("TreeSet removing time: " + duration +" nano seconds");

		treeSetInstance.add("element1");

		startTime = System.nanoTime();
		treeSetInstance.contains("element1");
		endTime = System.nanoTime();
		duration = endTime - startTime;
		System.out.println("TreeSet search: " + duration +" nano seconds");

		treeSetInstance.add("element2");

		startTime = System.nanoTime();
		Iterator iterator = treeSetInstance.descendingIterator();
			while (iterator.hasNext()) {
				System.out.println(iterator.next());
			}
		endTime = System.nanoTime();
		duration = endTime - startTime;
		System.out.println("TreeSet printing: " + duration +" nano seconds");
	}

}

The output of the above code example when executed is shown in the screenshot below.

TreeSet Performance

3. Download the Source Code

Download
You can download the full source code of this example here: Treeset Class Java Example

Bhagvan Kommadi

Bhagvan Kommadi is the Founder of Architect Corner & has around 20 years’ experience in the industry, ranging from large scale enterprise development to helping incubate software product start-ups. He has done Masters in Industrial Systems Engineering at Georgia Institute of Technology (1997) and Bachelors in Aerospace Engineering from Indian Institute of Technology, Madras (1993). He is member of IFX forum,Oracle JCP and participant in Java Community Process. He founded Quantica Computacao, the first quantum computing startup in India. Markets and Markets have positioned Quantica Computacao in ‘Emerging Companies’ section of Quantum Computing quadrants. Bhagvan has engineered and developed simulators and tools in the area of quantum technology using IBM Q, Microsoft Q# and Google QScript. He has reviewed the Manning book titled : "Machine Learning with TensorFlow”. He is also the author of Packt Publishing book - "Hands-On Data Structures and Algorithms with Go".He is member of IFX forum,Oracle JCP and participant in Java Community Process. He is member of the MIT Technology Review Global Panel.
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
Back to top button