1

I have situation where there is a HashMap as

Map<Integer,ArrayList> key = new HashMap<Integer,ArrayList>();

The array list has [rankOfCard,suitOfCard]

I want to sort this Map in such a way that If the value is

(1,[3,1])
(2,[2,4])
(3,[1,3])
(4,[1,2])
(5,[2,3])

Output should be :

(4,[1,2])
(3,[1,3])
(5,[2,3])
(2,[2,4])
(1,[3,1])

How can I achieve this ?

Meenakshi
  • 468
  • 3
  • 12
  • 31
  • 4
    It appears you are using an ArrayList when a class like `Card` would be better. HashMap is an unsorted map, I suspect you don't need to sort it, instead you want to *display* them in a particular order. – Peter Lawrey Jul 16 '12 at 12:50
  • Just what I was writing :) In Java you don't model a tuple with a `List`. – Marko Topolnik Jul 16 '12 at 12:51
  • @PeterLawrey I understand that you are asking me to use a class Card containing Rank and suit attribute . am I right ? – Meenakshi Jul 16 '12 at 13:06
  • @Meenakshi If that is what the data means, yes. This will make sorting the values more logical as well. – Peter Lawrey Jul 16 '12 at 15:03

2 Answers2

1

Iterate through entry set and Collection.sort(entry.value())

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
0

A Map is not sorted, so it's not the right data structure for your task. A SortedMap sorts on keys, so it's no good as well, since you want your map sorted by value.

Your question does not clarify what the key of the Map is, but maybe you could use a custom class in a regular List, and have the class implement the Comparable interface, or implement an external Comparator, to sort the List.

Flavio
  • 11,925
  • 3
  • 32
  • 36