I am trying to sort a map based on the value.
But I am seeing some weird behavior for the following program
public class CompareByValueMain {
public static void main(String[] args) {
Map<String,Integer> itemIDToTimeMap = new HashMap<String,Integer>();
itemIDToTimeMap.put("Baggage", 3);
itemIDToTimeMap.put("Handbag", 16);
itemIDToTimeMap.put("Closed Footwear", 4);
itemIDToTimeMap.put("Shirt", 25);
Set<String> itemIDs = itemIDToTimeMap.entrySet().stream()
.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
System.out.println(itemIDs);
}
}
The output is turned out to be correct
[Shirt, Handbag, Closed Footwear, Baggage]
But in the input when I change from Baggage to Bag It is giving the following output
[Shirt, Bag, Handbag, Closed Footwear]
Ideally sorting should be done based on the Value in the Map irrespective of the key values. But Not sure why it is changing if the key is changed here.