Java Utility Library

Java TreeMap - lowerEntry() Method



The java.util.TreeMap.lowerEntry() method returns a key-value mapping associated with the greatest key strictly less than the given key, or null if there is no such key.

Syntax

public Map.Entry<K,V> lowerEntry(K key)

Here, K and V are the type of key and value respectively maintained by the container.


Parameters

key Specify the key.

Return Value

Returns an entry with the greatest key less than key, or null if there is no such key.

Exception

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

Example:

In the example below, the java.util.TreeMap.lowerEntry() method returns the key-value mapping associated with the greatest key less than the given value.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a treemap
    TreeMap<Integer, String> MyMap = new TreeMap<Integer, String>();

    //populating the map
    MyMap.put(102, "John");
    MyMap.put(103, "Marry");
    MyMap.put(101, "Kim");
    MyMap.put(104, "Jo");
    MyMap.put(105, "Sam");

    //printing the map
    System.out.println("MyMap contains: " + MyMap); 

    //printing the key-value mapping for the 
    //greatest key less than key=103.
    System.out.println("Lower Entry for 103 is: " + MyMap.lowerEntry(103));     
  }
}

The output of the above code will be:

MyMap contains: {101=Kim, 102=John, 103=Marry, 104=Jo, 105=Sam}
Lower Entry for 103 is: 102=John

❮ Java.util - TreeMap