Jump to Real's How-to Main page

Sort an HashMap

Sort based on the keys
Map yourMap= new HashMap();
// put some tuples in yourMap ...
Map sortedMap = new TreeMap(yourMap);
Sort based on the values
HashMap yourMap = new HashMap();
// put some tuples in yourMap ...

// to hold the result
HashMap map = new LinkedHashMap();


List yourMapKeys = new ArrayList(yourMap.keySet());
List yourMapValues = new ArrayList(yourMap.values());
TreeSet sortedSet = new TreeSet(yourMapValues);
Object[] sortedArray = sortedSet.toArray();
int size = sortedArray.length;

for (int i=0; i<size; i++) {
   map.put
      (yourMapKeys.get(yourMapValues.indexOf(sortedArray[i])),
       sortedArray[i]);
}
To iterate your new Sorted Map
Set ref = map.keySet();
Iterator it = ref.iterator();

while (it.hasNext()) {
  String file = (String)it.next();
}

If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2007
[ home ]