Java TreeSet headSet(E toElement, boolean inclusive) Method Example

We have already seen the usage of headSet(E toElement) method of java.util.TreeSet class  which will return the view of the portion of this set whose elements are strictly less than toElement. where as headSet(E toElement, boolean inclusive) method will return a view of the portion of this set whose elements are less than or equal to if inclusive is true.

Signature

public NavigableSet<E> headSet(E toElement, boolean inclusive) 

This method returns a view of the portion of this set whose elements are less than or equal to if inclusive is true.Throws java.lang.ClassCastException if toElement is not compatible with this set’s comparator, java.lang.NullPointerException if toElement is null and this set uses natural ordering, or its comparator does not permit null elements and java.lang.IllegalArgumentException if this set itself has a restricted range, and toElement lies outside the bounds of the range

Example

The following example shows the usage of java.util.TreeSet.headSet(toElement,inclusive) method.

import java.util.TreeSet;

public class HeadSetIncludeMethodTreeSetExample 
{
    public static void main(String args[])
    {
        // Create treeSet and treeSetInc objects
        TreeSet treeSet = new TreeSet();
        TreeSet treeSetInc = new TreeSet();
        TreeSet treeSetNotInc = new TreeSet();
        
        //adding elements to TreeSet using add()
        treeSet.add(2);
        treeSet.add(4);
        treeSet.add(1);
        treeSet.add(3);
        treeSet.add(5);
        treeSet.add(7);
        treeSet.add(8);
        treeSet.add(6);
        treeSet.add(9);
        
        //Printing the elements of the TreeSet
        System.out.println("**Elements of the TreeSet**");
        for(Integer val : treeSet)
        {
            System.out.println(val);
        }
        
        //getting headSet of treeSet including 5
        treeSetInc = (TreeSet)treeSet.headSet(5, true);
        
        //Printing the elements of the treeSetInc
        System.out.println("**Elements of the treeSetInc**");
        for(Integer val : treeSetInc)
        {
            System.out.println(val);
        }
        
      //getting headSet of treeSet Not including 5
        treeSetNotInc = (TreeSet)treeSet.headSet(5, false);
        
        //Printing the elements of the treeSetNotInc
        System.out.println("**Elements of the treeSetNotInc**");
        for(Integer val : treeSetNotInc)
        {
            System.out.println(val);
        }
    }
}

Output

**Elements of the TreeSet**
1
2
3
4
5
6
7
8
9
**Elements of the treeSetInc**
1
2
3
4
5
**Elements of the treeSetNotInc**
1
2
3
4

Leave a Reply

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