TreeSet in Java with example

Here we will see about TreeSet in Java with example.

Basic points about TreeSet in Java.

  • TreeSet is a class which extends AbstractSet class(AbstractSet class further implements Set interface) and implements NavigableSet, Cloneable, Serializable interface.
  • TreeSet store the elements in Sorted order.
  • If we try to add null as an element in TreeSet, at compile time there is no issue but if we try to iterate the elements at runtime we will get NullPointerException.
  • We can’t have duplicate elements in TreeSet.
  • It stores the same types of elements.
  • We can iterate TreeSet using Iterator and for each loop. We can’t iterate TreeSet elements using ListIterator,Enumeration and normal for loop(as we don’t have get() method in TreeSet like ArrayList).
  •  None of the TreeSet methods are not synchronized.
  • TreeSet class internally uses TreeMap.
  • TreeSet objects are eligible for Serialization and cloning.

Example of TreeSet.

package treeset;

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

public class TreeSetExample {
	public static void main(String[] args) {
		Set<String> treeSetObj = new TreeSet<>();
		treeSetObj.add("ram");
		treeSetObj.add("mohan");
		treeSetObj.add("sohan");
		treeSetObj.add("rohan");
		treeSetObj.add("ram");
		System.out.println(treeSetObj);

	}
}

Output is – [mohan, ram, rohan, sohan]

Adding null as an element in TreeSet.

Let’s see an example, what will happen if we try to add null in TreeSet.

package treeset;

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

public class TreeSetExample {
	public static void main(String[] args) {
		Set<String> treeSetObj = new TreeSet<>();
		treeSetObj.add("ram");
		treeSetObj.add("mohan");
		treeSetObj.add("sohan");
		treeSetObj.add("rohan");
		treeSetObj.add(null);
		System.out.println(treeSetObj);

	}
}

Output is –

Exception in thread “main” java.lang.NullPointerException
at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
at treeset.TreeSetExample.main(TreeSetExample.java:13)

Since internally TreeSet perform sort operation adding null will result in NullPointerException.

Adding different types of element in TreeSet.

What will happen if we try to add different types of elements in TreeSet. For example, we will not define the generic type, can we add String as well as Integer? In the case of ArrayList, we can do no problem, what will happen in case of TreeSet. Let’s see an example. First, we will see an example for ArrayList then we will see an example of TreeSet.

Adding heterogeneous elements in ArrayList.

import java.util.ArrayList;

public class ArrayListDiffTypeElemt {
	public static void main(String[] args) {
		
		//As of now we are not defining generic type
		//Always remember in real time development 
		//we avoid to create object this way
		//we use generic
		
		ArrayList arrayListObj = new ArrayList();
		arrayListObj.add("ram");
		arrayListObj.add(10);
		arrayListObj.add(10.0f);
		System.out.println(arrayListObj);

	}
}

Output is – [ram, 10, 10.0]


In the case of ArrayList, we can have different types of elements.

Adding heterogeneous elements in TreeSet – At compile time there is no issue, but while running this program we will get ClassCastException.

import java.util.TreeSet;

public class TrreSetDiffTypeElemt {
	public static void main(String[] args) {

		// As of now we are not defining generic type
		// Always remember in real time development
		// we avoid to create object this way
		// we use generic

		TreeSet treeSetObj = new TreeSet();
		treeSetObj.add("ram");
		treeSetObj.add(10);
		treeSetObj.add(10.0f);
		System.out.println(treeSetObj);

	}
}

Output is –

Exception in thread “main” java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at java.lang.Integer.compareTo(Unknown Source)
at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
at ArrayListDiffTypeElemt.main(ArrayListDiffTypeElemt.java:13)

Now question aries why we gettig this exception in case of TreeSet, internally TreeSet try to sort the elements, for sorting it uses compareTo() method. As soon as it finds differnets types of elements it thorws ClassCastException.

Adding user define objects in TreeSet(Using Comparable).

If we try to add a user defined class in TreeSet, the class must implement the Comparable interface else we will get ClassCastException.

package addingcustomobjectintreeset;

import java.util.*;
class Book implements Comparable<Book>{
	
	private String bookName;
	private int id;
	
	
	public Book(int id, String bookName) {
		super();
		this.id = id;
		this.bookName = bookName;
	}
	
	public String getBookName() {
		return bookName;
	}
	public void setBookName(String bookName) {
		this.bookName = bookName;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}

	@Override
	public int compareTo(Book book) {
		
		int bookId = book.getId();
		return this.id - bookId;
	}	
}

public class Example {
public static void main(String[] args) {
	
	Set<Book> setOfBook = new TreeSet<>();
	setOfBook.add(new Book(3,"mahabharta"));
	setOfBook.add(new Book(2,"ramayana"));
	setOfBook.add(new Book(8,"alchemist"));
	setOfBook.add(new Book(4,"godan"));
	setOfBook.add(new Book(1,"panchtantra"));
	
	for(Book book: setOfBook) {
		System.out.println("book name is  "+book.getBookName() +" "+"book id is "+book.getId());
	}		
	
}
}

Output is –

book name is panchtantra book id is 1
book name is ramayana book id is 2
book name is mahabharta book id is 3
book name is godan book id is 4
book name is alchemist book id is 8

Note – We will get ClassCastException as Book class is not implementing Comparable interface.

Exception in thread “main” java.lang.ClassCastException: addingcustomobjectintreeset.Book cannot be cast to java.lang.Comparable
at java.util.TreeMap.compare(Unknown Source)
at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
at addingcustomobjectintreeset.Example.main(Example.java:38)

TreeSet Example in Java using Comparator.

package com.netsurfingzone;

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

class Student implements Comparator<Student> {

	private int id;
	private String name;

	public Student() {

	}

	public Student(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	// Ascending order
	@Override
	public int compare(Student s1, Student s2) {

		return s1.getName().compareTo(s2.getName());
	}

	// Descending order
	/*
	 * @Override public int compare(Student s1, Student s2) {
	 * 
	 * return s2.getName().compareTo(s1.getName()); }
	 */

}

public class TreeSetExampleUsingComparator {
	public static void main(String[] args) {

		Set<Student> students = new TreeSet<Student>(new Student());
		students.add(new Student(2, "john"));
		students.add(new Student(4, "rohn"));
		students.add(new Student(1, "paul"));
		students.add(new Student(2, "snow"));
		students.add(new Student(2, "victor"));
		students.add(new Student(2, "luna"));

		students.stream().forEach(
				(student) -> System.out.println("name is: " + student.getName() + "  Id is: " + student.getId()));

	}
}

Output is –

name is: john Id is: 2
name is: luna Id is: 2
name is: paul Id is: 1
name is: rohn Id is: 4
name is: snow Id is: 2
name is: victor Id is: 2


Converting a TreeSet to ArrayList and ArrayList to TreeSet.

ArrayList class has a constructor which can accept Collection as a parameter. Using this constructor we can convert TreeSet to ArrayList.

public ArrayList(Collection c) {

}

import java.util.*;

public class Test {
    public static void main(String args[]) {
        Set<String> set = new TreeSet<>();
        set.add("ran");
        set.add("mohan");
        set.add("sohan");

        List<String> list = new ArrayList<>(set);
        list.forEach(s -> System.out.println(s));
    }

}

Output is –

mohan
ran
sohan

TreeSet class has a constructor which can accept Collection as a parameter. Using this constructor we can convert ArrayList to TreeSet.

public TreeSet(Collection c) {

}

import java.util.*;

public class Test {
    public static void main(String args[]) {
        List<String> list = new ArrayList<>();
        list.add("ram");
        list.add("mohan");
        list.add("sohan");
        list.add("akash");

        Set<String> set = new TreeSet<>(list);
        set.forEach(s -> System.out.println(s));
    }

}

Output is –

akash
mohan
ram
sohan

HashSet vs TreeSet.

HashSetTreeSet
1. HashSet does not maintain any order.1. TreeSet maintains ascending order..
2. Hashset allows null value.2. In case of TreeSet if you add null value it will not give any compile time error but when you will try to iterate the elements it will throw NullPointerException.
3. Hashset is faster than TreeSet.3. TreeSet is slower than HashSet because it internally perform sorting operation.
4. Hashset internally uses HashMap4. TreeSet internally uses NavigableMap.
5. If we define generic type Object, in case of HashSet we can have different type of element.5. In case of TreeSet , we can't have different type of elements.

We will see more example TreeSet class in java with example.

Constructors of TreeSet in Java.

There are four constructors defined for TreeSet.

  • TreeSet()
  • TreeSet(Collection c)
  • TreeSet(Comparator comparator)
  • TreeSet(SortedSet sortedSet)

TreeSet() -This is default constructor which is used to create new and empty TreeSet, sort the added elements in ascending order. Intrnally this constructor uses TreeMap. Let’s see internal code of this constructor.

 
public TreeSet() {
        this(new TreeMap<E,Object>());
    }

Example 1.

package treeset;

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

public class TreeSetExample {
	public static void main(String[] args) {
		
		//TreeSet Object using default constructor
		Set<String> treeSetObj = new TreeSet<>();
		treeSetObj.add("ram");
		treeSetObj.add("mohan");
		treeSetObj.add("sohan");
		treeSetObj.add("rohan");
		System.out.println(treeSetObj);

	}
}

Output is – [mohan, ram, rohan, sohan]

TreeSet(Collection c) -We can pass any type of collection classes which implements Collections interface and can convert it into TreeSet. For example, we are going to convert ArrayList into TreeSet in below example before that let’s see how this constructor has been defined in TreeSet class.

Internal implementation –

public TreeSet(Collection<? extends E> c) {
        this();
        addAll(c);
    }

Example.

package treeset;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class TreeSetConstructorExap2 {
	public static void main(String[] args) {

		// Create a new TreeSet from different other collection classes
		// Here we will create TreeSet from ArrayList
		List<String> listObject = new ArrayList<>();

		listObject.add("ram");
		listObject.add("mohan");
		listObject.add("shyam");
		listObject.add("mohan");
		listObject.add("ram");
		System.out.println("before converting intp treeset-- " + listObject);

		// we have constructor TreeSet(Collection c), which can take any type
		// class as parameter which implements Collection interface
		Set<String> treeSetObj = new TreeSet<>(listObject);
		System.out.println("After converting into treeset-- " + treeSetObj);

	}
}

Output is –

before converting intp treeset– [ram, mohan, shyam, mohan, ram]
After converting into treeset– [shyam, mohan, ram]

TreeSet(Comparator comparator) -We can pass any class object which implements  Comparator interface.

Internal implementation.

 public TreeSet(Comparator<? super E> comparator) {
        this(new TreeMap<>(comparator));
    }

Example.

package treeset;

import java.text.Collator;
import java.util.Set;
import java.util.TreeSet;

public class TreeSetConstructorExap3 {
	public static void main(String[] args) {

		// Here we have Collator class which implements Comparator interface
		Collator myCollator = Collator.getInstance();
		
		//we have TreeSet constructor which can take Comparator 
		//below we are passing  myCollator object which internally 
		// implements Comparator interface
		Set<String> treeSetObj = new TreeSet<>(myCollator);
		treeSetObj.add("ram");
		treeSetObj.add("mohan");
		treeSetObj.add("sohan");
		treeSetObj.add("rohan");
		treeSetObj.add("ram");
		for (String str : treeSetObj) {
			System.out.println(str);
		}
	}
}

Output is –


mohan
ram
rohan
sohan

TreeSet(SortedSet sortedSet).

Internal implementation –

 public TreeSet(SortedSet s) {
        this(s.comparator());
        addAll(s);
    }

Example.

package treeset;

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

public class TreeSetConstructorExap4 {
	public static void main(String[] args) {

		Set<String> treeSetObj = new TreeSet<>();
		treeSetObj.add("ram");
		treeSetObj.add("mohan");
		treeSetObj.add("sohan");
		treeSetObj.add("rohan");
		treeSetObj.add("ram");

		// we have a constructor which can takes class object as parameter which
		// implements
		// SortedSet. Since TreeSet implements SortedSet interface we can pass
		// TreeSet itself. Although this doesn't make any sense but for
		// learning purpose we doing
		Set<String> treeSetObj1 = new TreeSet<String>(treeSetObj);

		for (String str : treeSetObj1) {
			System.out.println(str);
		}
	}
}

Output is –

mohan
ram
rohan
sohan

Iterating TreeSet in Java.

Using Iterator.

package treeset;

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

public class IteratingTreeSet {
	public static void main(String[] args) {
		Set<String> treeSetObj = new TreeSet<>();
		treeSetObj.add("ram");
		treeSetObj.add("mohan");
		treeSetObj.add("sohan");
		treeSetObj.add("rohan");
		treeSetObj.add("ram");
		Iterator<String> it = treeSetObj.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}

	}
}

Output is –

mohan
ram
rohan
sohan

Using for-each loop.

package treeset;

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

public class IteratingTreeSetSecWay {
	public static void main(String[] args) {
		Set<String> treeSetObj = new TreeSet<>();
		treeSetObj.add("ram");
		treeSetObj.add("mohan");
		treeSetObj.add("sohan");
		treeSetObj.add("rohan");
		treeSetObj.add("ram");
		for (String str : treeSetObj) {
			System.out.println(str);
		}
	}
}

Output is –

mohan
ram
rohan
sohan

Note – We can’t iterate TreeSet using Listiterator, Enumeration, and normal for loop(as we don’t have get() method in TreeSet like ArrayList).

Important methods Of TreeSet.

In this section, we will see some important methods of TreeSet in java with example.

TreeSet add(E e) method example – Adds the specified element to this set if it is not already present.

Example of add() method.

import java.util.TreeSet;

public class AddExample {
	public static void main(String[] args) {
		TreeSet<String> treeSet = new TreeSet<String>();
		treeSet.add("Komal");
		treeSet.add("Mohan");
		treeSet.add("Prativa");
		treeSet.add("Chandan");
		treeSet.add("Babita");
		treeSet.add("Trity");
		for (String str : treeSet) {
			System.out.println(str);
		}
		System.out.println("Iterating element with java 8 concept using forEach method");
		treeSet.forEach(str->System.out.println(str));
			
		}
	}

Output is :

Babita
Chandan
Komal
Mohan
Prativa
Trity
Iterating element with java 8 concept using forEach method
Babita
Chandan
Komal
Mohan
Prativa
Trity

TreeSet addAll(Collection c) method example Adds all of the elements in the specified collection to this set.

Example of addAll() method.

import java.util.TreeSet;

public class AddAllExample {

	public static void main(String[] args) {
		TreeSet<String> treeSet = new TreeSet<String>();
		treeSet.add("Komal");
		treeSet.add("Mohan");
		treeSet.add("Prativa");
		treeSet.add("Chandan");
		treeSet.add("Babita");
		treeSet.add("Trity");
		for (String str : treeSet) {
			System.out.println(str);
		}
		
		TreeSet<String> treeSet1 = new TreeSet<String>();
		treeSet1.add("Anupama");
		treeSet1.add("Sunita");
		treeSet1.addAll(treeSet);
		System.out.println("Iterating element with java 8 concept using forEach method");
		treeSet1.forEach(s->System.out.println(s));

	}

}

output is : –

Babita
Chandan
Komal
Mohan
Prativa
Trity
Iterating element with java 8 concept using forEach method
Anupama
Babita
Chandan
Komal
Mohan
Prativa
Sunita
Trity

TreeSet contains(Object o) method example Returns true if this set contains the specified element.

Example of contains() method.

import java.util.TreeSet;

public class ContainsExample {
public static void main(String[] args) {
	TreeSet<String> treeSet = new TreeSet<String>();
	treeSet.add("Komal");
	treeSet.add("Mohan");
	treeSet.add("Prativa");
	treeSet.add("Chandan");
	treeSet.add("Babita");
	treeSet.add("Trity");
	for (String str : treeSet) {
		System.out.println(str);
	}
System.out.println(treeSet.contains("Mohan"));	
System.out.println(treeSet.contains("Ankita"));	

}
}

output is :-

Babita
Chandan
Komal
Mohan
Prativa
Trity
true
false

TreeSet isEmpty() method example Returns true if this set contains no elements.

Example of isEmpty() method.

import java.util.TreeSet;

public class IsEmptyExample {

	public static void main(String[] args) {
		TreeSet<String> treeSet = new TreeSet<String>();
		System.out.println("before adding the elements in treeSet "+ treeSet.isEmpty());
		treeSet.add("Komal");
		treeSet.add("Mohan");
		treeSet.add("Prativa");
		treeSet.add("Chandan");
		treeSet.add("Babita");
		treeSet.add("Trity");
		for (String str : treeSet) {
			System.out.println(str);
		}
		
		System.out.println("after adding the elements in treeSet "+ treeSet.isEmpty());
	}

	}

output is : –

before adding the elements in treeSet true
Babita
Chandan
Komal
Mohan
Prativa
Trity
after adding the elements in treeSet false

TreeSet first() method example Returns the first (lowest) element currently in this set.

Example of first() method.

import java.util.TreeSet;

public class FirstExample {

	public static void main(String[] args) {
		TreeSet<String> treeSet = new TreeSet<String>();
		treeSet.add("Komal");
		treeSet.add("Mohan");
		treeSet.add("Prativa");
		treeSet.add("Chandan");
		treeSet.add("Babita");
		treeSet.add("Trity");
		for (String str : treeSet) {
			System.out.println(str);
		}
		System.out.println("first value in the TreeSet is " + treeSet.first());
	}

}

The output is:-

Babita
Chandan
Komal
Mohan
Prativa
Trity
first value in the TreeSet is Babita

TreeSet last() method example Returns the last (highest) element currently in this set.

Example of last() method.

import java.util.TreeSet;

public class LastExample {
	public static void main(String[] args) {
		TreeSet<String> treeSet = new TreeSet<String>();
		treeSet.add("Komal");
		treeSet.add("Mohan");
		treeSet.add("Prativa");
		treeSet.add("Chandan");
		treeSet.add("Babita");
		treeSet.add("Trity");
		for (String str : treeSet) {
			System.out.println(str);
		}
		System.out.println("Last value in the TreeSet is " + treeSet.last());
	}
}

The output is:-

Babita
Chandan
Komal
Mohan
Prativa
Trity
Last value in the TreeSet is Trity

TreeSet size() method example Returns the number of elements in this set (its cardinality).

Example of size() method.

import java.util.TreeSet;

public class SizeExample {

	public static void main(String[] args) {
		TreeSet<String> treeSet = new TreeSet<String>();
		treeSet.add("Komal");
		treeSet.add("Mohan");
		treeSet.add("Prativa");
		treeSet.add("Chandan");
		treeSet.add("Babita");
		treeSet.add("Trity");
		for (String str : treeSet) {
			System.out.println(str);
		}
		System.out.println("Size of TreeSet is " + treeSet.size());
	}
}

The output is:-

Babita
Chandan
Komal
Mohan
Prativa
Trity
Size of TreeSet is 6

TreeSet remove(Object o) method example Removes the specified element from this set if it is present.

Example of remove() method.

import java.util.TreeSet;

public class RemoveExample {
	public static void main(String[] args) {
		TreeSet<String> treeSet = new TreeSet<String>();
		treeSet.add("Komal");
		treeSet.add("Mohan");
		treeSet.add("Prativa");
		treeSet.add("Chandan");
		treeSet.add("Babita");
		treeSet.add("Trity");
		for (String str : treeSet) {
			System.out.println(str);
		}
		treeSet.remove("Trity");
		System.out.println("After removed element from treeset");
		treeSet.forEach(s->System.out.println(s));
	}
}

The output is :-

Babita
Chandan
Komal
Mohan
Prativa
Trity
After removed element from treeset
Babita
Chandan
Komal
Mohan
Prativa

TreeSet containsAll() method example – Checks any set contains all elements or not.

package com.netsurfingzone;

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

public class TreeSetContains {
	public static void main(String[] args) {

		// Create first setObject and add some elements
		Set<String> setObject = new TreeSet<String>();
		setObject.add("john");
		setObject.add("peter");
		setObject.add("topu");
		setObject.add("sansa");
		setObject.add("victor");

		// Create second setObject and add some elements - All elements same as
		// setObject
		Set<String> setObject1 = new TreeSet<String>();
		setObject1.add("john");
		setObject1.add("peter");
		setObject1.add("topu");
		setObject1.add("sansa");
		setObject1.add("victor");

		// Create third setObject and add some elements - Add only two elements
		Set<String> setObject2 = new TreeSet<String>();
		setObject2.add("john");
		setObject2.add("peter");

		// Create third setObject and add some elements - Add only two elements
		Set<String> setObject3 = new TreeSet<String>();
		setObject3.add("john");
		setObject3.add("snow");

		System.out.println(setObject.containsAll(setObject1));
		System.out.println(setObject.containsAll(setObject2));
		System.out.println(setObject.containsAll(setObject3));

	}
}

true
true
false

TreeSet descendingIterator() method example – Returns an iterator over the elements in this set in descending order.

package com.netsurfingzone;

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

public class TreeSetMethodExample {
	public static void main(String[] args) {

		//
		Set<String> setObject = new TreeSet<String>();
		setObject.add("john");
		setObject.add("peter");
		setObject.add("topu");
		setObject.add("sansa");
		setObject.add("victor");

		// Using descendingIterator() method - Returns Iterator which containd
		// set that is in desending order
		Iterator<String> descendingSet = ((TreeSet<String>) setObject).descendingIterator();
		while (descendingSet.hasNext()) {
			System.out.println(descendingSet.next());
		}

	}
}

Output is –

victor
topu
sansa
peter
john

That’s all about TreeSet in java with example.

You may like.

TreeSet java docs.

Summary – We have seen about TreeSet in java with example. Also covered constructors and methods of TreeSet in java.