What is the TreeMap.higherKey() method in Java?

In this shot, we will learn how to use the TreeMap.higherKey() method in Java.

Introduction

The TreeMap.higherKey() method is present in the TreeMap class inside the java.util package.

TreeMap.higherKey() is used to obtain the lowest key that is still greater than the given key in the parameter. If no such key is present in the TreeMap, the method returns null.

Syntax

The syntax of the TreeMap.higherKey() method is given below:

K higherKey(K Key);

Parameters

  • Key: The key for which we need to determine the least key from the TreeMap.

Return value

higherKey() returns the lowest key in the map that is greater than the given key in the parameter.

Code

Let’s have a look at the code.

import java.util.*;
class Main
{
public static void main(String[] args)
{
TreeMap<Integer, String> t1 = new TreeMap<Integer, String>();
t1.put(1, "Let's");
t1.put(5, "see");
t1.put(2, "TreeMap class");
t1.put(27, "methods");
t1.put(9, "in java.");
System.out.println("The least key greater than the given " +
"key present in the map is: " + t1.higherKey(4));
TreeMap<String, Integer> t2 = new TreeMap<String, Integer>();
t2.put("apple", 98);
t2.put("banana", 5);
t2.put("carrot", 2);
t2.put("dog", 27);
t2.put("elephant", 9);
System.out.println("The least key greater than the given " +
"key present in the map is: " + t2.higherKey("cat"));
}
}

Explanation

  • Line 1: We import the required package.

  • Line 2: We make a Main class.

  • Line 4: We make a main() function.

  • Line 6: We declare a TreeMap that consists of keys of type Integer and values of type String.

  • Lines 8-12: We use the TreeMap.put() method to insert values in the TreeMap.

  • Line 14: We use the TreeMap.higherKey() method and display the least key that is greater than the given key from the map with a message.

  • Lines 17-26: We define another TreeMap object so that the keys are of type String and the values are of type Integer. Now, we can see in the output that the least key that is greater than key=catkey = cat is displayed. This means that for string-based keys, the function returns the key based on alphabetical order.

So, this is the way to use the TreeMap.higherKey() method in Java.

Free Resources