Many questions have been asked in StackOverflow regarding sorting the Hashmap by key or value. Most of them are posted over many years. For example,this,this, and this. I am searching for any onliner method for sorting the Hashmap keys by their values and get the array of the sorted keys. In iOS, following line of code yields the same:
NSArray* sortedKeys = [myDictionary keysSortedByValueUsingSelector:@selector(compare:)]};
Here, if the NSDictionary
myDictionary contains the following objects:
{
S: 1;
A: 5;
N: 8;
T: 2;
O: 0;
}
Then the sortedKeys
contains the following objects:
(N, A, T, S, O)
Is such method available in the latest Java? Shall I follow the lengthy solutions? A lengthy solution given here yields a sorted Hashmap (keys sorted by their respective values). Will the order of the sorted keys still persists if I extract the keys of this sorted Hashmap using keySet()
?
Thank you!