0

Possible Duplicate:
How to sort a Map<Key, Value> on the values in Java?

I need to sort my hashmap according to the values stored in it. The hashmap contains the contacts name stored in phone.also I need that the keys get automatically sorted as soon as I sort the values.or you can say the keys and values are bounded together thus any changes in values should get reflected in keys.

 HashMap<Integer,String> map = new HashMap<Integer,String>();
    map.put(1,froyo);
    map.put(2,abby);
    map.put(3,denver);
    map.put(4,frost);
    map.put(5,daisy);

required output:

2,abby;
5,daisy;
3,denver;
4,frost;
1,froyo;
Community
  • 1
  • 1

1 Answers1

0
private static class MyMapComparator implements Comparator<Map.Entry<Integer, String>>
{
    @Override
    public int compare(Map.Entry<Integer, String> a, Map.Entry<Integer, String> b) {
        return a.getValue().compareTo(b.getValue());
    }
}
...

List<Map.Entry<Integer, String>> entries = new ArrayList<Map.Entry<Integer, String>>(map.entries());
Collections.sort(entries, new MyMapComparator());
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138