Middle
What does the sortedness of the SortedMap interface manifest in besides the toString() method displaying elements in sorted order?
sobes.tech AI
Answer from AI
The sorting of SortedMap manifests (besides toString()):
- Order of traversal and iteration: Iterators obtained from views (
entrySet,keySet,values) guarantee traversal of elements in key order. - Subset views: Methods
subMap(),headMap(),tailMap()allow obtaining subsets of the map based on a range of keys, and these subsets remain sorted. - Retrieving boundary elements: Methods
firstKey()andlastKey()allow obtaining the smallest and largest keys in the map (and, respectively, the first and last elements during iteration). - Presence of a comparator:
SortedMapcan be created using an explicitly specified comparator (Comparator) or use the natural ordering of keys (Comparable). The methodcomparator()returns the comparator used (ornullfor natural ordering).
Example:
// Using views
SortedMap<Integer, String> sortedMap = new TreeMap<>();
sortedMap.put(3, "Three");
sortedMap.put(1, "One");
sortedMap.put(2, "Two");
// Traversal in key order
for (Map.Entry<Integer, String> entry : sortedMap.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
// Getting a submap
SortedMap<Integer, String> subMap = sortedMap.subMap(1, 3); // Excluding key 3
System.out.println(subMap); // {1=One, 2=Two}
// Getting boundary keys
System.out.println("First key: " + sortedMap.firstKey()); // 1
System.out.println("Last key: " + sortedMap.lastKey()); // 3