Skip to content

Get First or Last Key Value or Entry from Java TreeMap Example

This example shows how to get first or last key, value, or entry from TreeMap in Java. This example also shows how to use firstEntry, firstKey, lastEntry, and lastKey methods of TreeMap class.

How to get first or last key, value, or entry from the TreeMap in Java?

How to get the first key from the TreeMap?

The firstKey method of the TreeMap class returns the first (i.e. the lowest) key from the map object.

The firstKey method throws NoSuchElementException exception if the TreeMap is empty. Make sure to check if TreeMap is not empty before calling this method.

Output

How to get the first entry from the TreeMap?

The firstEntry method of the TreeMap class returns the first entry (or the entry with the lowest key) from the map object.

The firstEntry method returns null if the map is empty.

Output

How to get the first value from the TreeMap?

There are no direct methods to get the first value from the TreeMap. You can use either the firstKey or the firstEntry method to get the first value from the TreeMap.

Output

How to get the last key from the TreeMap?

The lastKey method of the TreeMap class returns the last key (or the highest key) from the map object.

The lastKey method throws NoSuchElementException exception if the map is empty.

Output

How to get the last entry from the TreeMap?

The lastEntry method of the TreeMap class returns the last entry or the entry with the highest key in the map object.

The lastEntry method returns null if the TreeMap is empty.

Output

How to get the last value from the TreeMap?

Same as getting the fist value, there are no direct methods to get the last value (i.e. the value mapped to the lowest or the first key) from the TreeMap object. However, we can get the last value either by getting the last key or last entry.

Output

This example is a part of the TreeMap in Java Tutorial.

Please let me know your views in the comments section below.

References:
Java 8 TreeMap

About the author

Leave a Reply

Your email address will not be published.