0

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!

santobedi
  • 866
  • 3
  • 17
  • 39

1 Answers1

2

Using streams, you can write:

List<String> keys = map.entrySet().stream()
                      .sorted(Entry.comparingByValue())
                      .map(Entry::getKey)
                      .collect(toList());

It's a bit longer than your iOS example but not that bad.

To get the list in reverse order, you can use a reverse order comparator:

.sorted(Collections.reverseOrder(Entry.comparingByValue()))
assylias
  • 321,522
  • 82
  • 660
  • 783