Possible Duplicate:
How to sort a Map<Key, Value> on the values in Java?
Here's my handiwork:
ArrayList<Map.Entry<Integer, Integer>> suits = new ArrayList<Map.Entry<Integer, Integer>>();
suits.add(new AbstractMap.SimpleEntry(0, 3));
suits.add(new AbstractMap.SimpleEntry(1, 5));
suits.add(new AbstractMap.SimpleEntry(2, 1));
suits.add(new AbstractMap.SimpleEntry(3, 3));
Collections.sort(suits, new Comparator<Map.Entry<Integer, Integer>>() {
@Override
public int compare(Entry<Integer, Integer> e1, Entry<Integer, Integer> e2) {
if (e1.getValue() > e2.getValue())
return 1;
else if (e1.getValue() < e2.getValue())
return -1;
else if (e1.getKey() > e2.getKey())
return 1;
else if (e1.getKey() < e2.getKey())
return -1;
else
return 0;
}
});
It works (at least on the simple test case I included). It's intended to sort a hand of cards by number of cards (for example 3 spades, 5 hearts, 5 diamonds, 6 clubs), then proceed to do stuff with the suits we have less cards of (3 spades).
I have seen this problem of sorting a Map by value is a frequent one, and I had a little trouble understanding some of the answers provided elsewhere as I have absolutely no formal training in coding, nor in Java - so I made my own. Is anything blatantly wrong in this code? If it's not worth a daily WTF, it's good enough for me.
Thanks.