Java - TreeSet example

Posted on October 23, 2016


This tutorial shows how we can perform various operations on the TreeSet like

  • Adding an element into the TreeSet.
  • Removing an element from the TreeSet.
  • Printing the size of the TreeSet.
  • Checking if an element exists in the TreeSet or not.
  • Removing all elements from the TreeSet .

TreeSetExample.java

/**
 * 
 */
package com.boraji.tutorial;

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


/**
 * @author imssbora
 *
 */
public class TreeSetExample {
	public static void main(String[] args) {
		Set<String> set=new TreeSet<>();
		
		/*Adding elements into the TreeSet*/
		set.add("A");
		set.add("B");
		set.add("C");
		set.add("D");
		set.add("E");
		
		System.out.println("TreeSet elements:"+set);
		
		/*Removing an element from the TreeSet*/
		set.remove("A");
		System.out.println("TreeSet elements after removal:"+set);
		
		/*Printing the size of the TreeSet*/
		System.out.println("TreeSet size:"+set.size());
		
		/*Checking if an elements exist in the TreeSet or not*/
		System.out.println("Element 'D' exist in set:"+set.contains("D"));
		
		/*Removing all elements from the TreeSet*/
		set.clear();
		System.out.println("Element in TreeSet:"+set);
	}
}

Output

TreeSet elements:[A, B, C, D, E]
TreeSet elements after removal:[B, C, D, E]
TreeSet size:4
Element 'D' exist in set:true
Element in TreeSet:[]