2

Possible Duplicate:
TreeMap sort by value

Please have a look at the following code

import java.util.HashMap;
import java.util.Map;

public class Mapper
{
    Map mMap;

    public Mapper()
    {
        mMap = new HashMap();
        mMap.put("A",1);
        mMap.put("B",2);
        mMap.put("C",3);
        mMap.put("D",4);
        mMap.put("E",5);
        mMap.put("F",6);

    }
}

As you can see, the Map contains, 2 types of data. Now I need to sort it by value, great if possible to do in descending order, otherwise no issue, normal sort. But, you know something like following is not possible

Map<String, int> treeMap = new TreeMap<String, int>(mMap);

So, how can I sort this ? Please help.

Community
  • 1
  • 1
PeakGen
  • 21,894
  • 86
  • 261
  • 463

2 Answers2

2
Map<String, Integer> mMap = new HashMap<String, Integer>();
        mMap.put("A",1);
        mMap.put("B",2);
        mMap.put("C",3);
        mMap.put("D",4);
        mMap.put("E",5);
        mMap.put("F",6);


private static Map sortByComparator(Map unsortMap) {

        List list = new LinkedList(unsortMap.entrySet());

        // sort list based on comparator
        Collections.sort(list, new Comparator() {
            public int compare(Object o1, Object o2) {
                return ((Comparable) ((Map.Entry) (o1)).getValue())
                                       .compareTo(((Map.Entry) (o2)).getValue());
            }
        });


        Map sortedMap = new LinkedHashMap();
        for (Iterator it = list.iterator(); it.hasNext();) {
            Map.Entry entry = (Map.Entry) it.next();
            sortedMap.put(entry.getKey(), entry.getValue());
        }
        return sortedMap;
    }
Mohammod Hossain
  • 4,134
  • 2
  • 26
  • 37
0

Use TreeMap, if you want to sort by keys.

If you wish to sort a map by values, create a list of keys which are sorted by values.

you need a Comparator to sort keys by comparing corresponding values.

public static <K, V extends Comparable<? super V>> List<K> getKeysSortedByValue(Map<K, V> map) {
    final int size = map.size();
    final List<Map.Entry<K, V>> list = new ArrayList<Map.Entry<K, V>>(size);
    list.addAll(map.entrySet());
    final ValueComparator<V> cmp = new ValueComparator<V>();
    Collections.sort(list, cmp);
    final List<K> keys = new ArrayList<K>(size);
    for (int i = 0; i < size; i++) {
        keys.set(i, list.get(i).getKey());
    }
    return keys;
}

private static final class ValueComparator<V extends Comparable<? super V>>
                                     implements Comparator<Map.Entry<?, V>> {
    public int compare(Map.Entry<?, V> o1, Map.Entry<?, V> o2) {
        return o1.getValue().compareTo(o2.getValue());
    }
}
Rahul
  • 15,979
  • 4
  • 42
  • 63