Java TreeSet tailSet(E fromElement) Method Example

The tailSet(E fromElement) method of  java.util.TreeSet class returns a view of the portion of this set whose elements are greater than or equal to fromElement. The returned set is backed by this set, so changes in the returned set are reflected in this set, and vice-versa. The returned set supports all optional set operations that this set supports.

Signature

public 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. The returned set is backed by this set, so changes in the returned set are reflected in this set, and vice-versa. The returned set supports all optional set operations that this set supports. Throws  java.lang.IllegalArgumentException on an attempt to insert an element outside its range.

Example

The following example shows the usage of java.util.TreeSet.tailSet(fromElement) method.

import java.util.TreeSet;

public class TailSetMethodTreeSetExample 
{
    public static void main(String args[])
    {
        // create empty TreeSets
        TreeSet<Integer>  treeSet1 = new TreeSet<Integer>();
        
        // use add() method to add elements to the TreeSet
        treeSet1.add(1);
        treeSet1.add(2);
        treeSet1.add(3);
        treeSet1.add(4);
        treeSet1.add(5);
        treeSet1.add(6);
        treeSet1.add(7);
        treeSet1.add(8);
        
        System.out.println("**Elements of the treeSet1**");
        //Print the element of the treeset
        for(Integer val : treeSet1)
        {
            System.out.println(val);
        }
        
        //Lets get the tailset of elements of treeSet1 from 3
        System.out.println("**TailSet of elements from 3**");
        for(Integer val : treeSet1.tailSet(3))
        {
            System.out.println(val);
        }
    } 
}

Output

**Elements of the treeSet1**
1
2
3
4
5
6
7
8
**TailSet of elements from 3**
3
4
5
6
7
8

Leave a Reply

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