TreeSet Example in Java

  • TreeSet sorts the elements in the ascending order.
  • TreeSet extends AbstractSet and implements the NavigableSet interface.
  • TreeSet does not hold any duplicate elements, contains only unique elements like HashSet.
  • TreeSet is non-synchronized.
  • Iterator returned by TreeSet is fail-fast Iterator like HashSet and LinkedHashSet, it will throw ConcurrentModificationException if iterator is modified after it's creation.

In this example we will demonstrate mostly used methods of TreeSet.

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

public class TreeSetExample {
	public static void main(String[] args) {
		// Creating a TreeSet to add strings
		TreeSet<String> myTreeSet = new TreeSet<String>();

		// Printing the elements it contains

		// Iterating each element of myTreeSet using Iterator
		Iterator<String> iterator = myTreeSet.iterator();
		while (iterator.hasNext()) {
		// TreeSet maintains sorting order of elements, 
		//note:String class implements Comparable interface and overwrite compareTo method
		// above line prints : [Element1, Element2, Element3, Element4, Element5, Element6]
		//Returns the first or lowest element of the set.
		System.out.println("First Element: "+myTreeSet.first());
		//Returns the last  or highest element of the set.
		System.out.println("Last Element: "+myTreeSet.last());
		// contains method check whether the set contains the specified element
		// or not
		System.out.println(myTreeSet.contains("Element1")); // true
		System.out.println(myTreeSet.contains("Element9"));// false

		// Print the size of the set
		System.out.println("size: " + myTreeSet.size());

		// Remove an element from the set

		System.out.println("After removing Element1 : " + myTreeSet);

		// Removes all of the elements from this set
		System.out.println("After calling clear() : " + myTreeSet);
		//isEmpty() Returns true if the set contains no elements.
		System.out.println("is empty :"+myTreeSet.isEmpty());

[Element1, Element2, Element3] Element1 Element2 Element3 [Element1, Element2, Element3, Element4, Element5, Element6] First Element: Element1 Last Element: Element6 true false size: 6 After removing Element1 : [Element2, Element3, Element4, Element5, Element6] After calling clear() : [] is empty :true

Related Examples

Write a program to check if an input String is Palindrome or not?
Calculate the factorial of a given number using Java?
How to reverse a number in Java?
Write a program to convert from decimal to binary?
Producer Consumer Example in Thread
Write a program to reverse a String?

Receive Latest Java Examples in Your Email: