SortedMap

Sorted Map is a map that maintains its entries in ascending order., Sorted Map sorts the entries according to the keys' natural ordering or according to a comparator that is supplied when the sorted map is created.

Sorted maps are described by the SortedMap interface. TreeMap is an example of a sorted map.

SortedMap, whose generic type is SortedMap<K,V>, extends Map.

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

public class Main {
  public static void main(String[] args) {
    SortedMap<String, Integer> sortedMap = new TreeMap<String, Integer>();
    String[] officeSupplies = { "a", "b", "c", "d", "e" };
    
    int[] quantities = { 20, 30, 5, 10, 20 };
    for (int i = 0; i < officeSupplies.length; i++){
      sortedMap.put(officeSupplies[i], quantities[i]);
    }
      
    System.out.println(sortedMap);
    System.out.println(sortedMap.headMap("c"));
    System.out.println(sortedMap.headMap("c"));
    SortedMap<String, Integer> smsiCopy;
    Comparator<String> cmp;
    cmp = new Comparator<String>() {
      public int compare(String key1, String key2) {
        return key2.compareTo(key1); // descending order
      }
    };
    smsiCopy = new TreeMap<String, Integer>(cmp);
    smsiCopy.putAll(sortedMap);
    System.out.println(smsiCopy);
  }
}
  

{a=20, b=30, c=5, d=10, e=20}
{a=20, b=30}
{a=20, b=30}
{e=20, d=10, c=5, b=30, a=20}
Home 
  Java Book 
    Collection  

SortedMap:
  1. SortedMap
  2. SortedMap: firstKey()
  3. SortedMap: lastKey()