如果有多个最大值,如何在树图中找到按升序排列的键?

How I can find a key ordered in ascending order in treemap, if there are more than one max values?

我有一个 TreeMap 条目像

["aftab" = 4, "Manoj" = 5, "Rahul" = 5]

我想获取具有最大值的键,但如果有两个或更多最大值,我想要映射中第一个出现的键,在本例中为 Manoj。在我的应用程序中,我使用了 Collections.max(map.getKey()) 并且它返回 Rahul.

制作一个比较器,按值降序对条目进行排序,然后在两个值相等时按键进行比较

Entry.<String, Integer>comparingByValue().reversed()
.thenComparing(Entry.comparingByKey())
Map<String, Integer> map = new TreeMap<>();
map.put("aftab", 4);
map.put("Manoj", 5);
map.put("Rahul", 5);
Entry<String, Integer> result = map.entrySet().stream()
                .sorted(Entry.<String, Integer>comparingByValue().reversed().thenComparing(Entry.comparingByKey()))
                .findFirst().orElseGet(null);

System.out.println(result);

,输出

Manoj=5

创建一个 Comparator 并将其传递给 Collections.max()

Map<String, Integer> map = new TreeMap<>(
            Map.of("Aftab", 4, "Manoj", 5, "Rahul", 5));

Comparator<Entry<String,Integer>> comp = Entry.comparingByValue();

Entry<String,Integer> e = Collections.max(map.entrySet(),comp);

System.out.println(e);
// or
System.out.println(e.getKey());

使用Collections::max通过使用Comparator.comparingInt(Map.Entry::getValue)map.entrySet()中找到最大值的条目。

演示:

import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> map = new TreeMap<>();
        map.put("aftab", 4);
        map.put("Manoj", 5);
        map.put("Rahul", 5);

        Entry<String, Integer> entry = Collections.max(map.entrySet(), Comparator.comparingInt(Map.Entry::getValue));
        System.out.println(entry);
    }
}

输出:

Manoj=5