Junior — Middle
Can you explain the principle of operation of the SortedMap interface and how it differs from a regular Map?
sobes.tech AI
Answer from AI
The SortedMap interface in Java extends the regular Map and guarantees that the elements will be stored in sorted order by keys. Main differences:
- Order of elements: In
SortedMap, keys are ordered either by their natural ordering (if the keys implementComparable) or by a specified comparator. - Additional methods:
SortedMapprovides methods for obtaining sub-maps, such assubMap(),headMap(),tailMap(), as well as methods for accessing the first and last keys (firstKey(),lastKey()).
Example of using SortedMap:
import java.util.SortedMap;
import java.util.TreeMap;
public class SortedMapExample {
public static void main(String[] args) {
SortedMap<Integer, String> map = new TreeMap<>();
map.put(3, "Three");
map.put(1, "One");
map.put(2, "Two");
// Keys will be sorted: 1, 2, 3
for (Integer key : map.keySet()) {
System.out.println(key + " -> " + map.get(key));
}
}
}
Unlike a regular Map (for example, HashMap), where the order of elements is not guaranteed, SortedMap ensures key ordering.