Home » Core Java » util » TreeMap » Obtain lowest and highest keys from TreeMap example

About Ilias Tsagklis

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

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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

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