I have a Map<Object, String> that I need to sort with values in no particular order What I mean is currently the Map has the values like "A","B","C",D",E" for respective keys. I need to sort it as "C","D","E","A","B". I know we can write Comparator when there is some logic behind sorting. But I am not sure how to sort the Map this way.
That is not sorting. That is the opposite of sorting.
Maps do not support a recognisable ordering as a default. There are two kinds of Map which do,
The composite Map (well, I call it that), which contains both a Map and a List, whose Iterator returns K‑V pairs in order of first insertion.
The Sorted Map, whose Iterator returns pairs in ascending order of the value of the “K” (I think). A Map which iterates A‑B‑C‑D‑E sounds like a sorted Map.
I am not aware of any way to un‑sort a Map.
You can try putting all the elements into an ordinary Map (e.g. HashMap), but you will probably get things sorted by hash code in reverse bit order, so youmight still get A‑B‑C‑D‑E.
You can try loading all the pairs into a List and using the methods of the Collections class to randomise the order of that List. Then add all the elements back into a combined Map and List.
Ankit Chandrawat wrote:If I had known the reason or any sort of logic behind this I would have worked on writing a Comparator on this. But there is no logic to this and that's why I am baffled.
If you can't explain how the 'sort' is supposed to happen, then you can't tell the computer how to do it. You have to learn what the requirement means and understand its rules. Once you understand the rules enough that you can tell someone else how it is supposed to work - then you can think about programming it. Until then it is impossible.