TreeMap

Obtain lowest and highest keys from TreeMap example

In this example we shall show you how to obtain the lowest and highest keys from a TreeMap. The TreeMap API provides methods for these operations. To obtain the lowest and highest keys from a TreeMap one should perform the following steps:

  • Create a new TreeMap.
  • Populate the map with elements, with put(K key, V value) API method of TreeMap.
  • Invoke firstKey() API method of TreeMap. The method returns the first (lowest) key currently in this map.
  • Invoke lastKey() API method of TreeMap. The method returns the last (highest) key currently in this map,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;
 
import java.util.TreeMap;
 
public class LowHighKeyTreeMap {
 
  public static void main(String[] args) {
 
    // Create a TreeMap and populate it with elements
    TreeMap treeMap = new TreeMap();
    treeMap.put("key_1","element_1");
    treeMap.put("key_3","element_3");
    treeMap.put("key_2","element_2");
    treeMap.put("key_4","element_4");
    treeMap.put("key_5","element_5");
 
    // Object firstKey() returns the lowest key in the TreeMap 
    System.out.println("Lowest key in TreeMap is : "  + treeMap.firstKey());
 
    // Object lastKey() returns the highest key in the TreeMap 
    System.out.println("Highest key in TreeMap is : " + treeMap.lastKey());
 
  }
}

Output:

Lowest key in TreeMap is : key_1
Highest key in TreeMap is : key_5

 
This was an example of how to obtain the lowest and highest keys from a TreeMap in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button