Use TreeMap , which is an implementation of the SortedMap interface. He presents his keys in sorted order.
Map<String, Object> map = new TreeMap<String, Object>(); ... for (Map.Entry<String, ?> entry : map.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); }
If you are working with another map implementation that is not sorted as you see fit, you can pass it to the TreeMap constructor to create a new map with sorted keys.
void process(Map<String, Object> original) { Map<String, Object> copy = new TreeMap<String, Object>(original); ... }
A TreeMap works with any type of key that implements the Comparable interface, placing them in its βnaturalβ order. For keys that are not Comparable , or whose natural order is not what you need, you can implement your own Comparator and specify what is in the constructor.
erickson Feb 20 '09 at 21:59 2009-02-20 21:59
source share