Skip to content

Get Java TreeMap Key, Value, or Entry Greater or Less than the Specified Key Example

This example shows how to get the key, value, or an entry greater than or less than the specified key from the TreeMap in Java using the higherKey, higherEntry, lowerKey, lowerEntry, ceilingKey, ceilingEntry, floorKey, and floorEntry methods.

How to get a key from TreeMap that is less than the specified key?

There are a couple of ways using which we can get the key that is less than the specified key from the TreeMap.

1. Using the lowerKey method

The lowerKey method returns the greatest key from the TreeMap which is less than the specified key.

It returns null if there is no such key in the TreeMap object.

Output

2. Using the floorkey method

The floorKey method returns the greatest key from the TreeMap which is less than or equal to the specified key.

It returns null if there is no such key in the TreeMap object.

You can also use the lowerEntry and floorEntry methods instead of the lowerKey and floorKey methods respectively to get an entry instead of the key.

To get a value, get the entry and then use the getValue method of the Map.Entry to get value.

Output

How to get a key from TreeMap that is greater than the specified key?

There are a couple of ways using which we can get the key that is greater than the specified key from the TreeMap.

1. Using the higherKey method

The higherKey method returns the lowest key from the TreeMap that is greater than the specified key.

It returns null if there is no such key in the TreeMap object.

Output

2. Using the ceilingKey method

The ceilingKey method returns the lowest key from the TreeMap that is greater than or equal to the specified key.

It returns null if there is no such key in the TreeMap object.

Output

You can also use the higherEntry and ceilingEntry methods instead of the higherKey and ceilingKey methods respectively to get an entry instead of the key.

To get a value, get the entry and then use the getValue method of the Map.Entry to get value.

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.