Java TreeSet Example

nilan avtar
Nilanchala Panigrahy 馃尡

In the following example, we will see how to use TreeSet Collection in java. This example includes,

  • How to create an TreeSet
  • How to display element of Treeset
  • Adding data to TreeSet
  • Deleting data from TreeSet

Things to know about TreeSet

  1. TreeSet is similar to聽TreeMap聽that stores its elements in a tree and maintain order of its elements based on their values. The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.
  2. To get the size of TreeSet collection聽size()聽method is used.
  3. The size of the TreeSet can be determine by calling聽size()聽method.
  4. remove() method can be used to remove an item/object
  5. clear() method removes all object and makes the TreeSet empty
  6. first() and last() method is used to get the first and last element in TreeSet

TreeSet Example

import java.util.Iterator;
import java.util.TreeSet;

public class TreeSetExample {

	public static void main(String[] args) {
		// adding Integer to treeset
		TreeSet<Integer> treeSet = new TreeSet<Integer>();

		// Check empty or not
		if (treeSet.isEmpty()) {
			System.out.print("TreeSet is empty.");
		} else {
			System.out.println("TreeSet size: " + treeSet.size());

		// Looping and Displaying the Tree set data using Iterator
		Iterator<Integer> iterator = treeSet.iterator();
		while (iterator.hasNext()) {
			System.out.print( + "\t");

		// Retrieve first data from tree set
		System.out.println("\nFirst Element: " + treeSet.first());

		// Retrieve last data from tree set
		System.out.println("Last Element: " + treeSet.last());

		// remove element by value
		boolean flag = treeSet.remove(40);
		if (flag) {
			System.out.println("40 is removed!");
		} else {
			System.out.println("40 doesn't exist!");

		System.out.println("New size after delete: " + treeSet.size());

		// Looping and Displaying the Tree set data using Iterator
		iterator = treeSet.iterator();
		while (iterator.hasNext()) {
			System.out.print( + "\t");

		// Remove all data
		if (treeSet.isEmpty()) {
			System.out.print("\nTree Set is empty.");
		} else {
			System.out.println("\nTree Set size: " + treeSet.size());


TreeSet size: 5
20	22	30	40	50	
First Element: 20
Last Element: 50
40 is removed!
New size after delete: 4
20	22	30	50	
Tree Set is empty.

Sharing is caring!

Did you like what Nilanchala Panigrahy 馃尡 wrote? Thank them for their work by sharing it on social media.

nilan avtar

Nilanchala Panigrahy 馃尡

I'm a blogger, educator and a full stack developer. Mainly focused on Java, Spring and Micro-service architecture. I love to learn, code, make and break things.

Related articles