SortedMap in Java

SortedMap in Java is an interface in Collection Framework which provides a total ordering on its keys. The SortedMap interface extends Map interface. It ensures that the elements in the Map are ordered according to the natural ordering of its keys, or by a Comparator typically provided at sorted map creation time.

SortedMap in Java is generic and is declared as shown below:

interface SortedMap<K, V>

Here, K specifies the type of keys, and V specifies the type of values.

All the keys inserted into a sorted map must implement the Comparable interface.

Key points about SortedMap:

  • It doesn’t allow null keys and values.
  • Elements in the Map are ordered according to the natural ordering of its keys, or by a Comparator.

Example:

Let’s run this program and check the output.

Output:

In the above program, we have added key and values in the random order in SortedMap. With the help of Iterator, we have iterated the elements in the SortedMap. If you observe the output, the keys are sorted in the ascending order.

You can also learn about

Related posts

Leave a Comment