Java Utility Library

Java TreeSet - higher() Method



The java.util.TreeSet.higher() method returns the least element in this set strictly greater than the given element, or null if there is no such element.

Syntax

public E higher(E e)

Here, E is the type of element maintained by the container.


Parameters

e Specify the value to match.

Return Value

Returns the least element greater than e, or null if there is no such element.

Exception

  • Throws ClassCastException, if the specified element cannot be compared with the elements currently in the set.
  • Throws NullPointerException, if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements.

Example:

In the example below, the java.util.TreeSet.higher() method returns the least element in the given set strictly greater than the specified value.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a treeset
    TreeSet<Integer> MySet = new TreeSet<Integer>();

    //populating the set
    MySet.add(10);
    MySet.add(20);
    MySet.add(30);
    MySet.add(40);

    //printing the set
    System.out.println("MySet contains: " + MySet); 

    //printing the least element greater than 25
    System.out.println("Least Element greater than 25: " + MySet.higher(25));

    //printing the least element greater than 50
    System.out.println("Least Element greater than 50: " + MySet.higher(50));  
  }
}

The output of the above code will be:

MySet contains: [10, 20, 30, 40]
Least Element greater than 25: 30
Least Element greater than 50: null

❮ Java.util - TreeSet