Java TreeSet subSet() Method Example

The subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) method of java.util.TreeSet class returns a view of the portion of this set whose elements range from fromElement to toElement. If fromElement and toElement are equal, the returned set is empty unless fromInclusive and toInclusive are both true

Signature

public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive)

This method returns a view of the portion of this set whose elements range from fromElement to toElement. If fromElement and toElement are equal, the returned set is empty unless fromInclusive and toInclusive are both true. The returned set is backed by this set, so changes in the returned set are reflected in this set, and vice-versa. Throws java.lang.ClassCastException if if fromElement and toElement cannot be compared to one another using this set’s comparator, java.lang.NullPointerException if fromElement or toElement is null and this set uses natural ordering, or its comparator does not permit null elements and java.lang.IllegalArgumentException if fromElement is greater than toElement or if this set itself has a restricted range, and fromElement or toElement lies outside the bounds of the range

Example

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

import java.util.TreeSet;

public class SubSetMethodTreeSetExample 
{
    public static void main(String args[])
    {
        // create empty TreeSets
        TreeSet  treeSet1 = new TreeSet();
        TreeSet  treeSubSet1 = 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 elements between 2 to 4
        treeSubSet1 =(TreeSet)treeSet1.subSet(2,true,4,true);
        
        System.out.println("**Elements of the treeSubSet1**");
        //Print the element of the treeset
        for(Integer val : treeSubSet1)
        {
            System.out.println(val);
        }
    } 
}

Output

**Elements of the treeSet1**
1
2
3
4
5
6
7
8
**Elements of the treeSubSet1**
2
3
4

Leave a Reply

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