How to Get Lowest and Highest Key in Java TreeMap


The example aims to how to get the lowest and highest key stored in the java TreeMap.

Source Code

package com.beginner.examples;

import java.util.TreeMap;

public class GetLowestHighestKeyTreeMap {

	public static void main(String[] args) {
		
		//create TreeMap.
		TreeMap treeMap = new TreeMap();
		
		treeMap.put("1","Alice");
		treeMap.put("2","Bob");
		treeMap.put("3","Jack");
		
		/*
		 * To get the lowest key currently stored in Java TreeMap using firstKey method of TreeMap.
		 */
		System.out.println("Lowest key in TreeMap is : " + treeMap.firstKey());

		System.out.println("Highest key in TreeMap is : " + treeMap.lastKey());

	}

}

Output:

Lowest key in TreeMap is : 1
Highest key in TreeMap is : 3

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments