Share this page 

Sort an HashMapTag(s): Language


Sort based on the keys
Map yourMap= new HashMap();
// put some tuples in yourMap ...
Map sortedMap = new TreeMap(yourMap);
To sort only the keys :
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

...

    Map<String,java.io.File> theSimpsons = new HashMap<String,java.io.File>();
    theSimpsons.put("Bart", new java.io.File("Bart.jpg"));
    theSimpsons.put("Lisa", new java.io.File("Lisa.jpg"));
    theSimpsons.put("Marge", new java.io.File("Marge.jpg"));
    theSimpsons.put("Barney", new java.io.File("Barney.jpg"));
    theSimpsons.put("Homer", new java.io.File("Homer.jpg"));
    theSimpsons.put("Maggie", new java.io.File("Maggie.jpg"));

    SortedSet<String> sortedset= new TreeSet<String>(theSimpsons.keySet());

    Iterator<String> it = sortedset.iterator();

    while (it.hasNext()) {
      System.out.println (it.next());
    }
  
...

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();
}