SortedMap in Java
In the last blog, we learned about the class called TreeMap. If you want to learn more about it, visit TreeMap in Java. In this blog, we will go through the interface called SortedMap.
SortedMap
SortedMap interface extends Map. All the entries in the SortedMap are stored in ascending order. As SortedMap is an interface we can use it directly. In order to use the functionalities of the SortedMap, we can use TreeMap which implements the SortedMap. SortedMap is present in java.util package. We can create the SortedMap in the following way:
Methods of SortedMap
- comparator()
- firstKey()
- lastKey()
- headMap(Object end)
- tailMap(Object start)
- subMap(Object start, Object end)
The comparator() method produces a comparator that is used to order the keys in the SortedMap, or it returns null if the SortedMap's keys are ordered naturally.
e.g.
Output
firstKey() method returns the first key of the sorted map.
e.g.
Output
lastKey() method returns the last key of the sorted map.
e.g.
Output
headMap(Object end) returns the SortedMap that contains the elements that are less than the end of the SortedMap.
e.g.
Output
tailMap(Object start) returns all entries of the map whose keys are greater than or equal to the specified keys.
e.g.
Output
subMap(Object start, Object end) returns the SortedMap containing the elements between the start and end.
e.g.
Output