Curriculum
In Java, a SortedMap
is an interface that extends the Map
interface and provides a way to store key-value pairs in a sorted order. The keys are sorted based on their natural ordering or based on a custom comparator if one is provided. Here is an overview of SortedMap
along with examples and methods.
import java.util.SortedMap; import java.util.TreeMap; public class SortedMapExample { public static void main(String[] args) { // Creating a TreeMap (which implements SortedMap) with natural ordering SortedMap<Integer, String> map1 = new TreeMap<>(); map1.put(3, "Three"); map1.put(1, "One"); map1.put(5, "Five"); System.out.println(map1); // Output: {1=One, 3=Three, 5=Five} // Creating a TreeMap with custom comparator for sorting in reverse order SortedMap<Integer, String> map2 = new TreeMap<>((a, b) -> b.compareTo(a)); map2.put(3, "Three"); map2.put(1, "One"); map2.put(5, "Five"); System.out.println(map2); // Output: {5=Five, 3=Three, 1=One} } }
The following are some commonly used methods of SortedMap
interface:
Comparator<? super K> comparator()
: Returns the comparator used to order the keys in this map, or null if the natural ordering is used.K firstKey()
: Returns the first (lowest) key currently in this map.SortedMap<K, V> headMap(K toKey)
: Returns a view of the portion of this map whose keys are strictly less than toKey
.K lastKey()
: Returns the last (highest) key currently in this map.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> tailMap(K fromKey)
: Returns a view of the portion of this map whose keys are greater than or equal to fromKey
.SortedMap<Integer, String> map = new TreeMap<>(); map.put(1, "One"); map.put(2, "Two"); map.put(3, "Three"); map.put(4, "Four"); map.put(5, "Five"); // Using firstKey and lastKey methods System.out.println(map.firstKey()); // Output: 1 System.out.println(map.lastKey()); // Output: 5 // Using headMap method SortedMap<Integer, String> headMap = map.headMap(3); System.out.println(headMap); // Output: {1=One, 2=Two} // Using tailMap method SortedMap<Integer, String> tailMap = map.tailMap(4); System.out.println(tailMap); // Output: {4=Four, 5=Five} // Using subMap method SortedMap<Integer, String> subMap = map.subMap(2, 4); System.out.println(subMap); // Output: {2=Two, 3=Three}
Note that SortedMap
does not allow null keys but allows null values. If you attempt to add a null key to a SortedMap
, a NullPointerException
will be thrown.