Java TreeSet higher(E e) Method 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. where as higher(E e) method returns the least element in this set strictly greater than the given element, or null if there is no such element.

Signature

public E higher(E e) 

This method returns the least element greater than e or null if there is no such element

Example

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

import java.util.TreeSet;

public class HigherMethodTreeSetExample 
{
    public static void main(String args[])
    {
        // Create treeSet and treeSetInc objects
        TreeSet<Integer> treeSet = new TreeSet<Integer>();
                
        //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);
        }
        
        //Get the element greater than "6"
        System.out.println("**Element greater than \"6\" is **: "+treeSet.higher(6));
    }
}

Output

**Elements of the TreeSet**
1
2
3
4
5
6
7
8
9
**Element greater than "6" is **: 7

Leave a Reply

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