Java - Collection Framework Sorted Maps


A sorted map sorts the map entries on keys based on either natural sort order or a custom sort order.

If the keys do not implement the Comparable interface, you must use a Comparator object to sort the entries.

Comparator object takes precedence over Comparable interface implemented on keys.

SortedMap interface inherited from the Map interface represented a sorted map.

TreeMap class implements the SortedMap interface.

The following code demonstrates how to use a SortedMap.


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

public class Main {
  public static void main(String[] args) {
    SortedMap<String, String> sMap = new TreeMap<>();
    sMap.put("XML", "(342)113-1234");
    sMap.put("Javascript", "(245)890-2345");
    sMap.put("Json", "(205)678-3456");
    sMap.put("Java", "(205)678-3456");

    System.out.println("Sorted Map: " + sMap);

    // Get a sub map from Json (inclusive) to Java(exclusive)
    SortedMap<String, String> subMap = sMap.subMap("Json", "Java");
    System.out.println("Sorted Submap from Json to Java(exclusive): " + subMap);

    // Get the first and last keys
    String firstKey = sMap.firstKey();
    String lastKey = sMap.lastKey();
    System.out.println("First Key: " + firstKey);
    System.out.println("Last key: " + lastKey);
  }//  w  ww  .  jav  a2 s. c om


Related Topics