1

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.

Community
  • 1
  • 1
pouzzler
  • 1,800
  • 2
  • 20
  • 32
  • Nothing is blatantly wrong in the code. But it doesn't have to do a lot with `Map`; you just have a `List` of key-value pairs (as `Map.Entry` objects), not a `Map`. – Jesper Jan 16 '12 at 15:33
  • Your code would be much easier to read if you created a custom class to represent your card. – Mitch Jan 16 '12 at 15:36

1 Answers1

1

I suggest using a TreeMap with your comparator. You are right that sorting by value would be hard to do with TreeMap. You can follow Sort a Map<Key, Value> by values (Java) which suggests how to sort by value.

Community
  • 1
  • 1
Amir Raminfar
  • 33,777
  • 7
  • 93
  • 123