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 ?

4
  • 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. Commented Jul 16, 2012 at 12:50
  • Just what I was writing :) In Java you don't model a tuple with a List. Commented Jul 16, 2012 at 12:51
  • @PeterLawrey I understand that you are asking me to use a class Card containing Rank and suit attribute . am I right ? Commented Jul 16, 2012 at 13:06
  • @Meenakshi If that is what the data means, yes. This will make sorting the values more logical as well. Commented Jul 16, 2012 at 15:03

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.