Java SortedMap Interface

https:‮‬//www.theitroad.com

In Java, the SortedMap interface is a subinterface of the Map interface that represents a map that maintains its entries in sorted order based on the keys. The keys in a SortedMap are always sorted in ascending order according to their natural ordering, or according to a custom Comparator that is specified when the SortedMap is created.

The SortedMap interface provides several methods for working with the sorted map, such as firstKey(), lastKey(), subMap(), headMap(), and tailMap(). Here are some of the key methods of the SortedMap interface:

  • Comparator<? super K> comparator(): Returns the comparator used to order the keys in the SortedMap, or null if the natural ordering of the keys is used.

  • K firstKey(): Returns the first (lowest) key in the SortedMap.

  • K lastKey(): Returns the last (highest) key in the SortedMap.

  • SortedMap<K, V> subMap(K fromKey, K toKey): Returns a view of the portion of the SortedMap whose keys range from fromKey, inclusive, to toKey, exclusive.

  • SortedMap<K, V> headMap(K toKey): Returns a view of the portion of the SortedMap whose keys are less than toKey.

  • SortedMap<K, V> tailMap(K fromKey): Returns a view of the portion of the SortedMap whose keys are greater than or equal to fromKey.

SortedMap has several concrete implementations in the Java standard library, including TreeMap, which is a red-black tree-based implementation of the SortedMap interface. TreeMap provides guaranteed log(n) time cost for the containsKey(), get(), put(), and remove() operations, making it a good choice for sorted map implementations.