Java / Java 21 Collection Framework features Interview questions
How does TreeMap support SequencedMap given its comparator-based ordering?
Like TreeSet, TreeMap supports SequencedMap indirectly - it implements NavigableMap, and JEP 431 retrofitted NavigableMap to extend SequencedMap.
TreeMap already maintained entries in sorted order (natural ordering of keys, or via a supplied Comparator) and already had equivalent operations such as firstEntry(), lastEntry(), pollFirstEntry(), pollLastEntry(), and descendingMap().
TreeMap<String, Integer> ages = new TreeMap<>(); ages.put("Cid", 40); ages.put("Ann", 25); System.out.println(ages.firstEntry()); // Ann=25
What's new isn't the behavior itself, but that TreeMap now shares the exact same method names and contracts as LinkedHashMap, so code written against the general SequencedMap interface works identically on both.
More Related questions...