SortedMap In Java

SortedMap Interface in Java

The SortedMap interface in Java is a subinterface of the Map interface that provides a sorted collection of key-value pairs. It is used to store elements in a sorted order based on the natural ordering of keys or a custom comparator.

Key Features

  • Extends Map Interface: The SortedMap interface extends the Map interface, which means it inherits all the methods from the Map interface.
  • Sorted Order: Unlike the general Map interface, the SortedMap maintains the elements in a sorted order, either based on the natural ordering of keys or a custom comparator.
  • Additional Methods: The SortedMap interface provides additional methods for working with the sorted nature of the map, such as firstKey(), lastKey(), subMap(K fromKey, K toKey), headMap(K toKey), and tailMap(K fromKey).

Methods

The SortedMap interface includes all the methods from the Map interface, along with additional methods for sorted operations. Some of the important methods include:


V get(Object key)
V put(K key, V value)
V remove(Object key)
K firstKey()
K lastKey()
SortedMap<K, V> subMap(K fromKey, K toKey)
SortedMap<K, V> headMap(K toKey)
SortedMap<K, V> tailMap(K fromKey)

Example

Here's an example of using the SortedMap interface in Java:


import java.util.SortedMap;
import java.util.TreeMap;

public class SortedMapExample {
    public static void main(String[] args) {
        SortedMap>Integer, String< sortedMap = new TreeMap><();

        sortedMap.put(3, "Apple");
        sortedMap.put(1, "Orange");
        sortedMap.put(2, "Banana");

        for (Integer key : sortedMap.keySet()) {
            System.out.println(key  +" : " + sortedMap.get(key));
        }
        
    }
}

Output:

1 : Orange
2 : Banana
3 : Apple

In this example, we use the TreeMap class, which implements the SortedMap interface. We create a SortedMap of Integer keys and String values and add three key-value pairs to it. As TreeMap maintains the elements in sorted order based on the natural ordering of keys, the output shows the entries sorted by the keys in ascending order.

Conclusion

The SortedMap interface in Java provides a sorted collection of key-value pairs, allowing you to store elements in a specific order based on the natural ordering of keys or a custom comparator. It inherits all the methods from the Map interface and offers additional methods for sorted operations.

I hope this explanation helps you understand the SortedMap interface in Java! Let me know if you have any further questions.

List      Set      Queue      Map     TreeMap     Collection     Comparable Interface     Comparator Interface

Post a Comment

Previous Post Next Post