Java - print max of key value pair with custom logic

Killer Beast :

Lets assume I have a hashmap with data like :

Hello - 2
Help - 2
World - 1

I want to be able to print the top 2 based on the value, if the value is same for 2 objects then based on the key (ascending in this case). Is this possible only with a custom comparator object or are there better ways to get this done?

SDJ :

The requirement to have two comparison keys makes the solution non-trivial, but you can nevertheless specify the sorting order just by composing comparators returned by helper methods, saving you the trouble to write your own implementation.

The following shows a stream operation with in-lined comparator construction that performs the required selection.

List<Map.Entry<String, Integer>> result = map.entrySet().stream()
    .sorted(Map.Entry.<String, Integer>comparingByValue()
            .reversed()
            .thenComparing(Map.Entry::getKey))
    .limit(2)
    .collect(toList());

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=419924&siteId=1