Java Collection TreeSet headSet(E toElement) Example

The  headSet(E toElement)() method of java.util.TreeSet class will returns a view of the portion of this set whose elements are strictly less than toElement. 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> headSet(E toElement) 

This method returns a view of the portion of this set whose elements are strictly less than toElement. 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) method.

import java.util.TreeSet;

public class HeadSetMethodTreeSetExample 
{
    public static void main(String args[])
    {
        // Create treeSet1 and treeSet2 objects
        TreeSet treeSet1 = new TreeSet();
        TreeSet treeSet2 = new TreeSet();
        
        //adding elements to TreeSet using add()
        treeSet1.add(2);
        treeSet1.add(4);
        treeSet1.add(1);
        treeSet1.add(3);
        treeSet1.add(5);
        treeSet1.add(7);
        treeSet1.add(8);
        treeSet1.add(6);
        treeSet1.add(9);
        
        //Printing the elements of the TreeSet1
        System.out.println("**Elements of the TreeSet1**");
        for(Integer val : treeSet1)
        {
            System.out.println(val);
        }
        
        //add values before 5 of treeSet1 to treeSet2 using headSet() 
        treeSet2 = (TreeSet)treeSet1.headSet(5);
        
        //Printing the elements of the TreeSet2
        System.out.println("**Elements of the TreeSet2**");
        for(Integer val : treeSet2)
        {
            System.out.println(val);
        }
    }
}

Output

**Elements of the TreeSet1**
1
2
3
4
5
6
7
8
9
**Elements of the TreeSet2**
1
2
3
4

 

Leave a Reply

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