Java TreeSet Examples

TreeSet extends AbstractSet and implements NavigableSet interface. TreeSet is similar to HashSet except that it store element in sorted order.The sort order is either natural order or by a Comparator provided at creation time.It is not allowed null vallue.Java TreeSet Class is not synchronized . TreeSet class internally use TreeMap to store element.

TreeSet Hierarchy

Java TreeSet class extends AbstractSet class and implements NavigableSet interface. The NavigableSet interface extends SortedSet in hierarchical order. Declaration for HashSet class as below

public class TreeSet<E> extends AbstractSet<E>
    implements NavigableSet<E>, Cloneable, java.io.Serializable
{

    /**
     * The backing map.
     */
    private transient NavigableMap<E,Object> m;

    // Dummy value to associate with an Object in the backing Map
    private static final Object PRESENT = new Object();

   //more code 

}
java treeset class hierarchy
java treeset class hierarchy

HashSet Features

  • Java TreeSet cannot contain duplicate elements.
  • NULL is not allowed in TreeSet.
  • TreeSet internally uses a TreeMap to store elements.
  • The elements in a TreeSet are sorted as per natural ordering, or based on a given Comparator that is supplied at the time of creation of TreeSet.
  • TreeSet offers constant time performance for the basic operations(add, remove, size and contains), Like HashSet.
  • TreeSet is homogeous data stucture beause it sort element.
  • TreeSet class is not synchronized. You can use Collections.synchronizedSortedSet(new TreeSet())  method to get the synchronized TreeSet
    SortedSet s = Collections.synchronizedSortedSet(new TreeSet());
  • The iterators returned by HashTee class iterator method are fail-fast: if the set is modified at any time after the iterator is created,in any way except through the iterator’s own remove method, the iterator will throw a ConcurrentModificationException

Creating TreeSet And Adding elements to it

We can create java treeset class object using these constructors

  • TreeSet() – This Constructs a new, empty tree set, sorted according to the natural ordering of its elements.
  • TreeSet(Collection<? extends E> c) – This Constructs a new tree set containing the elements in the specified collection, sorted according to the natural ordering of its elements.
  • TreeSet(Comparator<? super E> comparator) – This Constructs a new, empty tree set, sorted according to the specified comparator.
  • TreeSet(SortedSet<E> s) – This Constructs a new tree set containing the same elements and using the same ordering as the specified sorted set.

We can add element element in Treeset using add() Method. Let’s see this by using code.

package com.demo;

import java.util.TreeSet;

public class TreeSetExample {
	
	public static void main(String[] args) {
		
	    /*
	     * Constructs a new, empty tree set, sorted according to the
	     * natural ordering of its elements
	     */
		TreeSet<String> treeSet = new TreeSet<String>();
		
		/*
		 * Adds the specified element to this set if it is not already present.
		 */
		treeSet.add("php");
		treeSet.add("java");
		treeSet.add("android");
		treeSet.add("spring");
		
		//display element of Treeset
		System.out.println("treeset is = "+ treeSet);
		
		//treeset for integers
		TreeSet<Integer> treeSetInt = new TreeSet<Integer>();
		
		//adding element in treeset
		treeSetInt.add(10);
		treeSetInt.add(20);
		treeSetInt.add(5);
		treeSetInt.add(15);
		
		//display tree's element 
		System.out.println("treeset is ="+ treeSetInt);
		
	}

}

Output:

treeset is = [android, java, php, spring]
treeset is =[5, 10, 15, 20]

Have you notice output ? Output show us that treeset store element in natural order . String TreeSet display element in alphabetically ascending order and Integer TreeSet display element in number ascending order.

Removing elements from a TreeSet

We can remove Element from TreeSet using remove() method.TreeSet provide pollFirst() and pollLast() method to return and remove first and last element respectively. Let’s see these thing with code

package com.demo;

import java.util.TreeSet;

public class TreeSetExample {
	
	public static void main(String[] args) {
		
	    /*
	     * Constructs a new, empty tree set, sorted according to the
	     * natural ordering of its elements
	     */
		TreeSet<String> treeSet = new TreeSet<String>();
		
		/*
		 * Adds the specified element to this set if it is not already present.
		 */
		treeSet.add("php");
		treeSet.add("java");
		treeSet.add("android");
		treeSet.add("mysql");
		treeSet.add("spring");
		
		//display element of Treeset
		System.out.println("treeset is = "+ treeSet);
		
		treeSet.remove("java");
		
		//display element 
		System.out.println("treeset after remove = "+ treeSet);
		
		/*
		 * Retrieves and removes the first (lowest) element, or
                   returns null if this set is empty.
		 */
	 	String element = treeSet.pollFirst();
	 	
	 	//displaying element 
	 	System.out.println("return element by pollFirst() ="+ element);
		
		//displaying element of TreeSet
		System.out.println("TreeSet After pollFirst ="+ treeSet);
		
		/*
		 * Retrieves and removes the last (highest) element, or 
                   returns null if this set is empty.
		 */
		String element2 = treeSet.pollLast();
		
		//displaying element 
		System.out.println("return element by pollLast() ="+ element2);
		
		
		//displaying element of TreeSet
		System.out.println("TreeSet After pollLast ="+ treeSet);
		
	}

}

Output:

treeset is = [android, java, mysql, php, spring]
treeset after remove = [android, mysql, php, spring]
return element by pollFirst() =android
TreeSet After pollFirst =[mysql, php, spring]
return element by pollLast() =spring
TreeSet After pollLast =[mysql, php]

TreeSet  Methods

  1. boolean add(E e) – This  Method Adds the specified element to this set if it is not already present.
  2. boolean addAll(Collection<? extends E> c) -This Method Adds all of the elements in the specified collection to this set.
  3. E ceiling(E e) – It returns the least element in this set greater than or equal to the given element, or null if there is no such element.
  4. void clear() – It removes all of the elements from this set.
  5. Object clone() – It returns a shallow copy of this TreeSet instance.
  6. Comparator<? super E> comparator() – This Method returns the comparator used to order the elements in this set, or null if this set uses the natural ordering of its elements.
  7. boolean contains(Object o) – This mehod returns true if this set contains the specified element.
  8. E first() – It returns the first (lowest) element currently in this set.
  9. E floor(E e) – It returns the greatest element in this set less than or equal to the given element, or null if there is no such element.
  10. boolean isEmpty() – This method returns true if this set contains no elements.
  11. Iterator<E> iterator() – This method returns an iterator over the elements in this set in ascending order.
  12. E last() – It returns the last (highest) element currently in this set.
  13. E pollFirst() – It retrieves and removes the first (lowest) element, or returns null if this set is empty.
  14. E pollLast() – It retrieves and removes the last (highest) element, or returns null if this set is empty.
  15. boolean remove(Object o) – It removes the specified element from this set if it is present.
  16. int size() – it returns the number of elements in this set (its cardinality).
  17. NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) – This method returns a view of the portion of this set whose elements range from fromElement to toElement.
  18. SortedSet<E> subSet(E fromElement, E toElement) – This method returns a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive.
  19. SortedSet<E> tailSet(E fromElement) – This method returns a view of the portion of this set whose elements are greater than or equal to fromElement.
  20. NavigableSet<E> tailSet(E fromElement, boolean inclusive) – This method returns a view of the portion of this set whose elements are greater than (or equal to, if inclusive is true) fromElement.

 

TreeSet Other Tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *

43 − = 40