Site icon JavaGoal

TreeSet Methods in Java

JavaTreeSet class provides various methods to perform on TreeSet. In this post, we will discuss several methods with java TreeSet example. Here we will discuss all the TreeSet methods in java.

Here is the table content of the article will we will cover this topic.
Insert Elements to TreeSet
1. add(E e) method
2. addAll(Collection c) method
Remove element from TreeSet
3. remove(Object o) method
4. pollFirst() method
5. pollLast() method
6. clear() method
Get the element from TreeSet
7. first() method
8. last() method
9. lower(E ele) method
10. floor(E ele) method
11. ceiling(E e) method
12. higher​(E e) method
How to get SubSet from TreeSet
13. SortedSet subSet(E fromElement, E toElement) method
14. NavigableSet subSet(E fromElement, E fromInclusive , E toElement, E toInclusive) method
15. SortedSet headSet(E toElement) method
16.SortedSet tailSet(E fromElement) method
17. NavigableSet headSet(E toElement, boolean inclusive) method
18. NavigableSet tailSet(E fromElement, boolean inclusive) method
19. descendingSet​() method

Insert Elements to TreeSet

We have two methods to insert elements in TreeSet. A TreeSet doesn’t accept duplicate elements and sorts the element. When we insert the element in TreeSet, it compares each element and maintains the order of elements.

1. add(E e) method

The add(E e) method inserts the specified element in TreeSet. It returns false if the element already exists.  It throws NullPointerException if we try to add null in TreeSet. It internally adds the element in TreeMap.

boolean add(E e);

Where, E represents the type of elements in TreeSet.
e is the element which you want to add in this TreeSet.
return type:  Its return type is boolean. It can return either true or false.
throws, ClassCastException if the specified object can’t be compared with the elements currently in TreeSet.
throws NullPointerException if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements.

import java.util.TreeSet;

public class TreeSetExample
{
    public static void main(String arg[])
    {
    	TreeSet<String> treeSet = new TreeSet<String>();
    	treeSet.add("Hi");
    	treeSet.add("Java");
    	treeSet.add("Goal");
    	treeSet.add("Learning");
    	
    	boolean isAddSuccessfully = treeSet.add("Website");
    	System.out.println("Is added successfully: "+ isAddSuccessfully);
    	
    	isAddSuccessfully = treeSet.add("Website");
    	System.out.println("Is added successfully: "+ isAddSuccessfully);
    	
    	System.out.println("Elements from TreeSet: "+ treeSet);
    }	
}

Output: Is added successfully: true
Is added successfully: false
Elements from TreeSet: [Goal, Hi, Java, Learning, Website]

2. addAll(Collection c) method

It adds all the elements of the specified collection in TreeSet. It maintains the sort order as in the given collection. It throws NullPointerException if given collection is null.

boolean addAll(Collection<? extends E> c);

Where, c is the collection which you want to add in this TreeSet.
return type:  Its return type is boolean. It can return either true or false.
throws, ClassCastException if the object from specified collection can’t be compared with the elements currently in TreeSet.
throws, NullPointerException if the object from specified collection is null and this set uses natural ordering, or its comparator does not permit null elements.

import java.util.TreeSet;

public class TreeSetExample
{
    public static void main(String arg[])
    {
    	TreeSet<String> treeSet = new TreeSet<String>();
    	treeSet.add("Hi");
    	treeSet.add("Java");
    	treeSet.add("Goal");
    	treeSet.add("Learning");
    	
    	TreeSet<String> newTreeSet = new TreeSet<String>();
    	newTreeSet.addAll(treeSet);
    	
    	System.out.println("Elements from TreeSet: "+ newTreeSet);
    }	
}

Output: Elements from TreeSet: [Goal, Hi, Java, Learning]

Remove element from TreeSet

TreeSet has remove() method that is used to remove the element from TreeSet.

3. remove(Object o) method

It removes the specified element from TreeSet. It returns after removing of elements otherwise false. It throws NullPointerException if the specified element is null.  

boolean remove(Object obj);

Where, Object represents the type of class in TreeSet.
obj is the element which you want to remove from the TreeSet.
return type:  Its return type is boolean. It can return either true or false.

import java.util.TreeSet;

public class TreeSetExample
{
    public static void main(String arg[])
    {
    	TreeSet<String> treeSet = new TreeSet<String>();
    	treeSet.add("Hi");
    	treeSet.add("Java");
    	treeSet.add("Goal");
    	treeSet.add("Learning");
    	
    	boolean isRemoved = treeSet.remove("Goal");
    	
    	System.out.println("Is removed sucessfully: "+isRemoved);
    	
    	System.out.println("Elements from TreeSet: "+ treeSet);
    }	
}

Output: Is removed sucessfully: true
Elements from TreeSet: [Hi, Java, Learning]

4. pollFirst() method

This method is used to get and remove the first element from the TreeSet. It will be the lowest element of TreeSet. If TreeSet is null, it will throw NoSuchElementException. This method performs two operations, It returns the first element from the TreeSet and removes that element from TreeSet.

Let’s say we have a TreeSet containing elements 1, 3, 7, 12, 18. If, we are calling pollFirst() method, it will return 1 and remove 1 from the TreeSet. This method checks lowest(First) element in TreeSet.

import java.util. TreeSet;
public class TreeSetExample 
{

    public static void main(String[] args) 
    {
        TreeSet<Integer> treeSet = new TreeSet<Integer>();
        treeSet.add(1);
        treeSet.add(3);
        treeSet.add(7);
        treeSet.add(12);
        treeSet.add(18);
        
        System.out.println("Elements of TreeSet: "+ treeSet);
        
        System.out.println("First element from TreeSet: "+treeSet.pollFirst());
        
        System.out.println("After removal :"+ treeSet);
      }
}

Output: Elements of TreeSet: [1, 3, 7, 12, 18]
First element from TreeSet: 1
After removal :[3, 7, 12, 18]

5. pollLast() method

This method is used to get and remove the last element from the TreeSet. It will be the greatest element of TreeSet. If TreeSet is null, it will throw NoSuchElementException.
It performs two operations in TreeSet, it returns the last element from the TreeSet and removes that element from TreeSet.

Let’s say we have a TreeSet containing elements 1, 3, 7, 12, 18. If we are calling pollLast() method, it will return 18 and remove 18 from the TreeSet. This method checks the greatest (Last) element in TreeSet.

import java.util. TreeSet;
public class TreeSetExample 
{

    public static void main(String[] args) 
    {
        TreeSet<Integer> treeSet = new TreeSet<Integer>();
        treeSet.add(1);
        treeSet.add(3);
        treeSet.add(7);
        treeSet.add(12);
        treeSet.add(18);
        
        System.out.println("Elements of TreeSet: "+ treeSet);
        
        System.out.println("Last element from TreeSet: "+treeSet.pollLast());
        
        System.out.println("After removal :"+ treeSet);
      }
}

Output: Elements of TreeSet: [1, 3, 7, 12, 18]
Last element from TreeSet: 18
After removal :[1, 3, 7, 12]

6. clear() method

This method is used to remove all the elements from the TreeSet. Its return type is void. It means this method doesn’t return anything.

void clear();

import java.util.TreeSet;
public class TreeSetExample 
{
    public static void main(String[] args) 
    {
        TreeSet<String> treeSetNames = new TreeSet<String>();
        
        treeSetNames.add("JAVA");
        treeSetNames.add("GOAL");
        treeSetNames.add("LEARNING");
        treeSetNames.add("SITE");
        
        // Before clear() method
        System.out.println("Name from TreeSet = "+treeSetNames);
        
        // Removing all the element by clear() method
        treeSetNames.clear();
        
        System.out.println("After Clear() method treeSet is empty : "+ treeSetNames.isEmpty());
        
    }
}

Output: Name from TreeSet = [GOAL, JAVA, LEARNING, SITE]
After Clear() method treeSet is empty : true

Get the element from TreeSet

TreeSet has various method those are used to get the element from TreeSet.

7. first() method

This method returns the first element from the TreeSet. It throws NoSuchElementException if TreeSet is empty.

E first();

Where E, represents the type of objects in TreeSet.
throws NoSuchElementException, if TreeSet is NULL.

import java.util.TreeSet;

public class TreeSetExample
{
    public static void main(String arg[])
    {
    	TreeSet<String> treeSet = new TreeSet<String>();
    	treeSet.add("Hi");
    	treeSet.add("Java");
    	treeSet.add("Goal");
    	treeSet.add("Learning");
    	treeSet.add("Website");
    	
    	System.out.println("First element from TreeSet: "+ treeSet.first());
    }	
}

Output: First element from TreeSet: Goal

8. last() method

It returns the last element from the TreeSet. If TreeSet is empty, It throws NoSuchElementException.

E last();

Where E, represents the type of objects in TreeSet.
throws NoSuchElementException, if TreeSet is NULL.

import java.util.TreeSet;

public class TreeSetExample
{
    public static void main(String arg[])
    {
    	TreeSet<String> treeSet = new TreeSet<String>();
    	treeSet.add("Hi");
    	treeSet.add("Java");
    	treeSet.add("Goal");
    	treeSet.add("Learning");
    	treeSet.add("Website");
    	
    	System.out.println("Last element from TreeSet: "+ treeSet.last());
    }	
}

Output: Last element from TreeSet: Website

9. lower(E ele) method

This method returns the closest least element of the specified element from the TreeSet. If TreeSet is null, it will throw NoSuchElementException.
If you are specifying any element e, Then TreeSet will return the element which will be the closest least element to e.

Let’s say we have a TreeSet containing elements 1, 3, 7, 12, 18. If we are calling lower(3) method, it will return 1. The specified element is 3 so this method checks the closest least element in TreeSet. If we are calling lower(8) method, it will return 7. The specified element is 8 so this method checks the closest least element in TreeSet. When we are calling lower(1), it returns null.

import java.util. TreeSet;
public class TreeSetExample 
{
    public static void main(String[] args) 
    {
        TreeSet<Integer> treeSet = new TreeSet<Integer>();
        treeSet.add(1);
        treeSet.add(3);
        treeSet.add(7);
        treeSet.add(12);
        treeSet.add(18);
        
        System.out.println("Element from TreeSet is: "+treeSet.lower(3));
        System.out.println("Element from TreeSet is: "+treeSet.lower(8));
        System.out.println("Element from TreeSet is: "+treeSet.lower(1));
    }
}

Output: Element from TreeSet is: 1
Element from TreeSet is: 7
Element from TreeSet is: null

10. floor(E ele) method

This method returns the equal or closest least element of the specified element from the Treeset. If TreeSet is null, it will throw NoSuchElementException.
If you are specifying any element e, Then TreeSet will return the element which will be equals to e or closest least element to e.

Let’s say we have a TreeSet containing elements 1, 3, 7, 12, 18. If we are calling floor(3) method, it will return 3. The specified element is 3 so this method checks the element in TreeSet. If we are calling floor(8) method, it will return 7. The specified element is 8 which doesn’t exist in TreeSet. So, this method checks the closest greatest element in TreeSet.

import java.util. TreeSet;
public class TreeSetExample 
{
    public static void main(String[] args) 
    {
    	TreeSet<Integer> treeSet = new TreeSet<Integer>();
	    treeSet.add(1);
	    treeSet.add(3);
	    treeSet.add(7);
	    treeSet.add(12);
	    treeSet.add(18);
	    
	    System.out.println("Element from TreeSet is = "+treeSet.floor(3));
	    System.out.println("Element from TreeSet is = "+treeSet.floor(8));
	    System.out.println("Element from TreeSet is = "+treeSet.floor(1));
	}
}

Output: Element from TreeSet is = 3
Element from TreeSet is = 7
Element from TreeSet is = 1

11. ceiling(E e) method

This method returns the equal or closest greatest element of the specified element from the Treeset. If TreeSet is null, it will throw NoSuchElementException.
If you are specifying any element e, Then TreeSet will return the element which will be equals to e or closest greatest element to e.

Let’s say we have a TreeSet containing elements 1, 3, 7, 12, 18. If we are calling ceiling(3) method, it will return 3. The specified element is 3 so this method checks the element in TreeSet. If, we are calling ceiling(5) method, it will return 7. The specified element is 7 which doesn’t exist in TreeSet. So, this method checks the closest greatest element in TreeSet.

import java.util. TreeSet;
public class TreeSetExample 
{
    public static void main(String[] args) 
    {
        TreeSet<Integer> treeSet = new TreeSet<Integer>();
        treeSet.add(1);
        treeSet.add(3);
        treeSet.add(7);
        treeSet.add(12);
        treeSet.add(18);
        
        System.out.println("Element from TreeSet is = "+treeSet.ceiling(3));
        System.out.println("Element from TreeSet is = "+treeSet.ceiling(5));
        System.out.println("Element from TreeSet is = "+treeSet.ceiling(18));
    }
}

Output:  Element from TreeSet is = 3
Element from TreeSet is = 7
Element from TreeSet is = 18

12. higher​(E e) method

This method returns the closest greatest element of the specified element from the TreeSet. If TreeSet is null, it will throw NoSuchElementException.
If you are specifying any element e, Then TreeSet will return the element which will be the closest greatest element to e.

Let’s say we have a TreeSet containing elements 1, 3, 7, 12, 18. If we are calling higher(3) method, it will return 7. The specified element is 3 so this method checks the closest greatest element in TreeSet. If we are calling higher(8) method, it will return 12. The specified element is 7 so this method checks the closest greatest element in TreeSet.

import java.util. TreeSet;
public class TreeSetExample 
{
    public static void main(String[] args) 
    {
    	TreeSet<Integer> treeSet = new TreeSet<Integer>();
        treeSet.add(1);
        treeSet.add(3);
        treeSet.add(7);
        treeSet.add(12);
        treeSet.add(18);
        
        System.out.println("Element from TreeSet is = "+treeSet.higher(3));
        System.out.println("Element from TreeSet is = "+treeSet.higher(8));
        System.out.println("Element from TreeSet is = "+treeSet.higher(18));
    }
}

Output: Element from TreeSet is = 7
Element from TreeSet is = 12
Element from TreeSet is = null

How to get SubSet from TreeSet

We can get a subset from TreeSet by use of some methods. We will discuss various methods.

13. SortedSet subSet(E fromElement, E toElement) method

This method returns the group of elements of TreeSet which ranging from fromElement to toElement. It includes the fromElement and excludes the toElement. Its return type is SortedSet.
throws ClassCastException, if elements are not compatible.
throws NullPointerException if toElement is null.
throws IllegalArgumentException, if the parameter is not correct of illegal.

Let’s say we have a TreeSet containing elements 1, 2, 3, 4, 5. If we are calling subSet (1, 4) method, it will return a group of elements that contain 1,2,3.

import java.util. TreeSet;
public class TreeSetExample 
{

    public static void main(String[] args) 
    {
    	  TreeSet<Integer> treeSet = new TreeSet<Integer>();
          treeSet.add(1);
          treeSet.add(2);
          treeSet.add(3);
          treeSet.add(4);
          treeSet.add(5);
          
          SortedSet<Integer> subSet = treeSet.subSet(1, 4);
          System.out.println("Elements from Subset: "+ subSet);
      }
}

Output: Elements from Subset: [1, 2, 3]

14. NavigableSet subSet(E fromElement, E fromInclusive , E toElement, E toInclusive) method

It returns the group of elements of TreeSet which ranging from fromElement to toElement. The programmer can include and exclude the fromElement and toElement by set the value true and false. Its return type is SortedSet.
throws ClassCastException, if elements are not compatible.
throws NullPointerException if toElement is null.
throws IllegalArgumentException, if parameter is not correct of illegal.

Let’s say we have a TreeSet containing elements 1, 2, 3, 4, 5. If we are calling subSet (1, true, 4, true) method, it will return a group of elements that contain 1,2,3,4. If we are calling subSet (1, false, 4, false) method, it will return a group of elements that contain 2,3.

import java.util. TreeSet;
public class TreeSetExample 
{

    public static void main(String[] args) 
    {
    	  TreeSet<Integer> treeSet = new TreeSet<Integer>();
          treeSet.add(1);
          treeSet.add(2);
          treeSet.add(3);
          treeSet.add(4);
          treeSet.add(5);
          
          NavigableSet<Integer> subSet = treeSet.subSet(1, true, 4, true);          
          System.out.println("Elements from Subset: "+ subSet);
      }
}

Output: Elements from Subset: [1, 2, 3, 4]

15. SortedSet headSet(E toElement) method

This method returns the group of elements of TreeSet which are less than the specified element. Its return type is SortedSet.
throws ClassCastException, if elements are not compatible.
throws NullPointerException if toElement is null.
throws IllegalArgumentException, If parameter is not correct of illegal.

Let’s say we have a TreeSet containing elements 1, 2, 3, 4, 5. If, we are calling headSet(4) method, it will return group of elements that contain 1,2,3.

import java.util. TreeSet;
public class TreeSetExample 
{

    public static void main(String[] args) 
    {
    	  TreeSet<Integer> treeSet = new TreeSet<Integer>();
          treeSet.add(1);
          treeSet.add(2);
          treeSet.add(3);
          treeSet.add(4);
          treeSet.add(5);
          
          SortedSet<Integer> subSet = treeSet.headSet(4);          
          System.out.println("Elements from Subset: "+ subSet);
      }
}

Output: Elements from Subset: [1, 2, 3]

16. SortedSet tailSet(E fromElement) method

This method returns the group of elements of TreeSet which are greater than the specified element. Its return type is SortedSet.

Let’s say we have a TreeSet containing elements 1, 2, 3, 4, 5. If we are calling tailSet(3) method, it will return a group of elements that contain 4,5.

import java.util. TreeSet;
public class TreeSetExample 
{

    public static void main(String[] args) 
    {
    	  TreeSet<Integer> treeSet = new TreeSet<Integer>();
          treeSet.add(1);
          treeSet.add(2);
          treeSet.add(3);
          treeSet.add(4);
          treeSet.add(5);
          
          SortedSet<Integer> subSet = treeSet.tailSet(4);          
          System.out.println("Elements from Subset: "+ subSet);
      }
}
Elements from Subset: [4, 5]

17. NavigableSet headSet(E toElement, boolean inclusive) method

This method returns the group of elements of TreeSet which are less than or equals to the specified element (if the inclusive parameter is true). It takes two parameters one is toElement and inclusive. It returns the object of NavigableSet.
throws ClassCastException, if elements are not compatible.
throws NullPointerException if toElement is null.
throws IllegalArgumentException, if the parameter is not correct of illegal.

Let’s say we have a TreeSet containing elements 1, 2, 3, 4, 5. If we are calling headSet(4, true) method, it will return a group of elements that contain 1,2,3,4. If we are calling headSet(4, false) method, it will return a group of elements that contain 1,2,3.

import java.util.NavigableSet;
import java.util.SortedSet;
import java.util. TreeSet;
public class TreeSetExample 
{

    public static void main(String[] args) 
    {
    	  TreeSet<Integer> treeSet = new TreeSet<Integer>();
          treeSet.add(1);
          treeSet.add(2);
          treeSet.add(3);
          treeSet.add(4);
          treeSet.add(5);
          
          NavigableSet<Integer> subSet = treeSet.headSet(4, true);     
          System.out.println("Elements from Subset: "+ subSet);
      }
}

Output: Elements from Subset: [1, 2, 3, 4]

18. NavigableSet tailSet(E fromElement, boolean inclusive) method

This method returns the group of elements of TreeSet which are greater than or equals to the specified element (if the inclusive parameter is true). It takes two parameters one is fromElement and inclusive. It returns the object of NavigableSet.
throws ClassCastException, if elements are not compatible.
throws NullPointerException if fromElement is null.
throws IllegalArgumentException, if the parameter is not correct of illegal.

Let’s say we have a TreeSet containing elements 1, 2, 3, 4, 5. If we are calling tailSet(3, true) method, it will return a group of elements that contain 3,4,5. If we are calling tailSet(3, false) method, it will return a group of elements that contain 4,5.

import java.util.NavigableSet;
import java.util.SortedSet;
import java.util. TreeSet;
public class TreeSetExample 
{

    public static void main(String[] args) 
    {
    	  TreeSet<Integer> treeSet = new TreeSet<Integer>();
          treeSet.add(1);
          treeSet.add(2);
          treeSet.add(3);
          treeSet.add(4);
          treeSet.add(5);
          
          NavigableSet<Integer> subSet = treeSet.tailSet(4, true);     
          System.out.println("Elements from Subset: "+ subSet);
      }
}

Output: Elements from Subset: [4, 5]

19. descendingSet​() method

This method returns a Treeset but all the elements of Treeset will be in reverse order view. It returns the object of NavigableSet.

Let’s say we have a TreeSet containing elements 1, 2, 3, 4, 5. If we are calling descendingSet() method, it will return all elements of TreeSet in reverse order. i.e. 5,4,3,2,1.

import java.util.NavigableSet;
import java.util.SortedSet;
import java.util. TreeSet;
public class TreeSetExample 
{

    public static void main(String[] args) 
    {
    	  TreeSet<Integer> treeSet = new TreeSet<Integer>();
          treeSet.add(1);
          treeSet.add(2);
          treeSet.add(3);
          treeSet.add(4);
          treeSet.add(5);
          
          NavigableSet<Integer> descendingSet = treeSet.descendingSet();    
          System.out.println("Elements from Subset: "+ descendingSet);
      }
}

Output: Elements from Subset: [5, 4, 3, 2, 1]

Exit mobile version