Sobes.tech
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()):

  1. Order of traversal and iteration: Iterators obtained from views (entrySet, keySet, values) guarantee traversal of elements in key order.
  2. Subset views: Methods subMap(), headMap(), tailMap() allow obtaining subsets of the map based on a range of keys, and these subsets remain sorted.
  3. Retrieving boundary elements: Methods firstKey() and lastKey() allow obtaining the smallest and largest keys in the map (and, respectively, the first and last elements during iteration).
  4. Presence of a comparator: SortedMap can be created using an explicitly specified comparator (Comparator) or use the natural ordering of keys (Comparable). The method comparator() returns the comparator used (or null for 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