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,> theSimpsons = new HashMap<String,>();
    theSimpsons.put("Bart", new"Bart.jpg"));
    theSimpsons.put("Lisa", new"Lisa.jpg"));
    theSimpsons.put("Marge", new"Marge.jpg"));
    theSimpsons.put("Barney", new"Barney.jpg"));
    theSimpsons.put("Homer", new"Homer.jpg"));
    theSimpsons.put("Maggie", new"Maggie.jpg"));

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

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

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

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++) {
To iterate your new Sorted Map
Set ref = map.keySet();
Iterator it = ref.iterator();

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

blog comments powered by Disqus