TreeMap in Java
In the previous blog, we learned about the Map interface in Java. To learn more about Map interface, visit Map Interface in Java. In this blog, we will learn about a class called TreeMap which implements the Map interface.
TreeMap
TreeMap uses a tree to implement the Map interface. TreeMap is used for storing the elements in key-value pairs in sorted order. TreeMap, unlike HashMap, assures that the elements are sorted in ascending order. It contains only unique elements. TreeMap cannot have null keys but can have multiple null values.
Syntax for Creating TreeMap
Methods of TreeMap
- put()
- putAll()
- keySet()
- values()
- get()
- getOrDefault()
- remove(Object k)
- firstKey()
- lastKey()
- higherKey()
- higherEntry()
- lowerKey()
- lowerEntry()
- ceilingKey()
- ceilingEntry()
- floorEntry()
put() method is used to insert or add an entry to the Map.
The putAll() method inserts or adds the specified map to the map.
Example of TreeMap using the methods put() and putAll()
Output
keySet() method returns the collection of keys exist in the map.
values() method returns a set of all the maps of a TreeMap.
get() method returns the object that contains the value associated with the key.
getOrDefault() method returns the value to which the specified key is mapped, or if no value is found, it returns defaultValue.
Example of TreeMap using the methods keySet(), values(), get(), getOrDefault()
Output
remove(Object k) method removes the entry from the map represented by the key k.
e.g.
Output
firstKey() method is used to return the first key currently in the map.
lastKey() method is used to return the last key currently in the map.
Example of TreeMap using firstKey() and lastKey()
Output
higherKey() method returns the lowest key among those keys that are greater than the specified key.
higherEntry() method returns the lowest key strictly greater than the given key or returns null if there is no such key.
lowerKey() method returns the greatest key amongst all the keys that are less than the given key
lowerEntry() method returns a key-value mapping associated with the greatest key amongst all keys which are less than the given key.
The ceilingKey() method returns the lowest key that is greater than the specified key, or it returns null if no such key is discovered.
The ceilingEntry() method returns the key-value pair with the lowest key that is larger than or equal to the specified key, or it returns null if no such key is discovered.
floorEntry() method returns the greatest key, less than or equal to the specified key, or returns null if there is no such key found.
Example of TreeMap using the above methods
Output