TreeMap: Fetching and Removal
Let's see how we can fetch and remove elements from a TreeMap.
We'll cover the following
Fetching an element from a TreeMap
The following methods can be used to fetch elements from a TreeMap.
Fetching the value for a particular key
We can fetch the value for a particular key using the get(Object o)
method. This method will return the value of the key if the key is present. If the key is not present, it will return null.
Fetching the smallest key
As we are aware that a TreeMap stores elements in sorted order, we can fetch the smallest key using the firstKey()
method. If the TreeMap is empty, then NoSuchElementException
is thrown. If we want to get the smallest entry, then the firstEntry()
method can be used.
Fetching the largest key
We can fetch the largest key using the lastKey()
method. If the TreeMap is empty, then NoSuchElementException
is thrown. If we want to get the largest entry, then the lastEntry()
method can be used.
Get hands-on with 1400+ tech skills courses.