Example of the java.util.SortedMap interface

The interface java.util.SortedMap  is a subtype of the interface java.util.Map  It ensures that the entries are sorted in ascending order.

By default, items are scanned in ascending order from the small value to the large value. But it is also possible to browse the elements in descending order with the method TreeMap.descendingKeySet().

The API Collections of java has only one implementation of the interface SortedMap which is the java.util.TreeMap.

Example:

import java.util.*; 

public class SortedMap {

public static void main(String[] args) {
// create a TreeMap with a generic type
TreeMap tm = new TreeMap();
// fill treemap
tm.put(1, "one");
tm.put(2, "two");
tm.put(3, "three");
tm.put(4, "four");
tm.put(5, "five");

// retrieve all keys
Set set = tm.entrySet();
// retrieve iterator
Iterator it = set.iterator();
// browse treemap to display elements
while(it.hasNext()) {
Map.Entry mapentry = (Map.Entry)it.next();
System.out.print("["+mapentry.getKey() +", ");
System.out.println(mapentry.getValue()+"]");
}
}
}
Results:

[1, one]
[2, two]
[3, three]
[4, four]
[5, five]