Last Updated: 06 March, 2023
SortedMap is an interface in the Java collection framework. SortedMap was introduced in the JDK 1.2 version and is available in the java.util package.
SortedMap extends the Map interface and stores the elements in the form of key-value pairs. SortedMap ensures that the entries are maintained in ascending key order.
The java.util.TreeMap class implements SortedMap interface in Java.
Java SortedMap declaration:
Here, K is the key Object type and V is the value Object type.
Methods | Description |
Comparator<? super K> comparator() | Returns the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys. |
SortedMap<K,V> subMap(K fromKey, K toKey) | Returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive. |
SortedMap<K,V> headMap(K toKey) | Returns a view of the portion of this map whose keys are strictly less than toKey. |
SortedMap<K,V> tailMap(K fromKey) | Returns a view of the portion of this map whose keys are greater than or equal to fromKey. |
K firstKey() | Returns the first (lowest) key currently in this map. |
K lastKey() | Returns the last (highest) key currently in this map. |
Set | Returns a Set view of the keys contained in this map. |
Collection | Returns a Collection view of the values contained in this map. |
Set<Map.Entry<K,V>> entrySet() | Returns a Set view of the mappings contained in this map. |
Output
SortedMap Elements:{31=Netherlands, 49=Germany, 65=Singapore, 81=Japan, 91=India}
The value associated with the key: Germany
SortedMap Elements after Remove:
{31=Netherlands, 65=Singapore, 81=Japan, 91=India}
SortedMap Elements after updating using put() method:
{31=Netherlands, 65=Singapore, 81=Japan-JP, 91=India}
SortedMap Elements after updating using replace() method:
{31=Netherlands, 65=Singapore-SG, 81=Japan-JP, 91=India}
SortedMap Elements after adding new key/value:
{31=Netherlands, 54=Argentina, 65=Singapore-SG, 81=Japan-JP, 91=India}
SortedMap Elements after adding new map:
{31=Netherlands, 54=Argentina, 65=Singapore-SG, 81=Japan-JP, 91=India, 263=Zimbabwe, 358=Finland, 973=Bahrain}
Output
SortedMap Elements: {31=Netherlands, 49=Germany, 65=Singapore, 81=Japan, 91=India}
Size of map: 5
Value of specified key (49): Germany
Is map is empty: false
first (lowest) key: 31
Last (highest) key: 91
Keys contained in this map: [31, 49, 65, 81, 91]
Values contained in this map: [Netherlands, Germany, Singapore, Japan, India]
Sub Map elements: {49=Germany, 65=Singapore}
SortedMap Elements: {}
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/SortedMap.html
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com