In this shot we will learn how to use the TreeMap.lowerEntry()
method in Java.
The TreeMap.lowerEntry()
method is present in the TreeMap
class inside the java.util
package.
TreeMap.lowerEntry()
is used to obtain the key-value pair associated with the greatest key that is strictly less than the given key in the parameter currently present in the map.
If no such key is present in the TreeMap
, the method returns null
.
The syntax of the TreeMap.lowerEntry()
method is given below:
Map.entry lowerEntry(K Key);
Key
: The key for which we need to determine the key-value pair from the TreeMap
.Entry
: The key-value pair associated with the greatest key that is strictly less than the given key in the parameter.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 key-value mapping associated with " +"the greatest key in the map is: " + t1.lowerEntry(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 key-value mapping associated with " +"the greatest key in the map is: " + t2.lowerEntry("cat"));}}
In line 1, we import the required package.
In line 2, we make a Main
class.
In line 4, we make a main()
function.
In line 6, we declare a TreeMap
that consists of keys of type Integer
and values of type String
.
From lines 8-12, we use the TreeMap.put()
method to insert values in the TreeMap
.
In line 14, we use the TreeMap.lowerEntry()
method and display the key-value pair associated with the greatest key that is less than the given key, along with a message.
From lines 17-26, we define another TreeMap
object such that the keys are of type String
and the values are of type Integer
. Now, we can see in the output that we display the greatest key-value pair that is less than the key = cat
. This means that for string-based keys, the function returns the key-value pair based on alphabetical order.
So, this is the way to use the TreeMap.lowerEntry()
method in Java.