Tech and Media Labs
This site uses cookies to improve the user experience.

Java Collections - SortedMap

Jakob Jenkov
Last update: 2014-06-23

The java.util.SortedMap interface is a subtype of the java.util.Map interface, with the addition that the elements stored in the map are sorted internally.

The order of the sorting is either the natural sorting order of the elements (if they implement java.lang.Comparable), or the order determined by a Comparator that you can give to the SortedSet.

By default the elements are iterated in ascending order, starting with the "smallest" and moving towards the "largest". But it is also possible to iterate the elements in descending order using the method TreeMap.descendingKeySet().

The Java Collections API only has one implementation of the SortedMap interface - the java.util.TreeMap class. The java.util.concurrent package also has an implementation of this interface, but I will leave the concurrency utilities out of this trail.

Here are two examples of how to create a SortedMap:

SortedMap mapA = new TreeMap();

Comparator comparator = new MyComparator();
SortedMap mapB = new TreeMap(comparator);

More Details in the JavaDoc

There is actually a lot more you can do with a TreeMap that is not part of the SortedMap interface, like getting a descending key set etc. Check out the JavaDoc's for more detail about these features.

Jakob Jenkov

Copyright  Jenkov Aps
Close TOC