Java Collection How to - Get Sorted keys from TreeMap








Question

We would like to know how to get Sorted keys from TreeMap.

Answer

/*from   w  w  w .j a  v a2 s .  c  om*/
import java.util.TreeMap;

public class Main {
  public static void main(String[] a) {

    TreeMap map = new TreeMap();
    map.put("key1", "value1");
    map.put("key2", "value2");
    map.put("key3", "value3");

    if (!map.isEmpty()) {
      Object last = map.lastKey();
      boolean first = true;
      do {
        if (!first) {
          System.out.print(", ");
        }
        System.out.print(last);
        last = map.headMap(last).lastKey();
        first = false;
      } while (last != map.firstKey());
      System.out.println();
    }
  }
}

The code above generates the following result.