Java TreeSet tailSet(E fromElement, boolean inclusive) 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 (if inclusive is true) 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 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 (if inclusive is true) 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,inclusive) method.

import java.util.TreeSet;

public class TailSetMethodTreeSetExample 
{
    public static void main(String args[])
    {
        // create empty TreeSets
        TreeSet  treeSet1 = new TreeSet();
        
        // 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 from 3
        System.out.println("**TailSet of elements from 3 inclusive as TRUE**");
        for(Integer val : treeSet1.tailSet(3,true))
        {
            System.out.println(val);
        }
        
        //Lets set the inclusive to false
        System.out.println("**TailSet of elements from 3 inclusive as FALSE**");
        for(Integer val : treeSet1.tailSet(3,false))
        {
            System.out.println(val);
        }
    } 
}

Output

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

Leave a Reply

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