Share on Google+Share on Google+

Java Collection : TreeSet Example

This tutorial contains description of TreeSet with example.

Java Collection : TreeSet Example

This tutorial contains description of  TreeSet with example.

TreeSet  :

TreeSet class is defined in java.util package. It is implementation of the Set interface and stores elements in tree. TreeSet stores elements in ascending order. It is sorted in natural order or by the comparator. Since it provides fast access and fast retrieval so it is better choice when you need large amount of sorted data.

It provides following constructor - TreeSet(), TreeSet(Collection c), TreeSet(Comparator c), TreeSet(SortedSet s)

Methods : There are various method of TreeSet. Some of them are -

  • add(Object o) : It adds the given item to the set if it is not already in the set.
  • addAll(Collection c) : This method adds all the element of given collection to the set.
  • first(): It returns the first element of your sorted set.
  • iterator() : It returns an iterator over the elements of the set.
  • remove(Object o) : It removes the given item from the set if it is in the set.

Other  methods are - clear(), clone(), comparator(), contains(Object o), headSet(Object toElement), isEmpty(), last(),  size(), subSet(Object fromElement, Object toElement), tailSet(Object fromElement).

Example :

package collection;

import java.util.TreeSet;

class TreeSetExample{
public static void main(String[] args){
//Creating object of TreeSet
TreeSet<Integer> treeSet=new TreeSet<Integer>();

//Adding elements to the TreeSet

System.out.println("After adding elements - ");
System.out.println("Size of TreeSet : "+treeSet.size());
System.out.println("Elements of TreeSet : "+treeSet);

//Removing elements

System.out.println("After deleting elements - ");
System.out.println("Size of TreeSet : "+treeSet.size());
System.out.println("Elements of TreeSet : "+treeSet);


Description : In this example we are using TreeSet to maintain set of sorted integer values.
Create object of TreeSet as - TreeSet<Integer> treeSet=new TreeSet<Integer>();
For adding element to the TreeSet we are using add(element) method .size() method calculate the number of elements in the TreeSet. You can print value of TreeSet by directly calling object of TreeSet. It will display the set of all element which is sorted in ascending order.
remove(200) method delete 200 from your set.

Output :

After adding elements - 
Size of TreeSet : 5
Elements of TreeSet : [111, 200, 300, 444, 600]
After deleting elements - 
Size of TreeSet : 3
Elements of TreeSet : [111, 300, 600]



Posted on: November 19, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null