Java 如果有多个max值,如何在treemap中找到按升序排列的键?

Java 如果有多个max值,如何在treemap中找到按升序排列的键?,java,treemap,Java,Treemap,我有一个TreeMap,其中包含如下条目 ["aftab" = 4, "Manoj" = 5, "Rahul" = 5] 我希望获得具有最大值的键,但是如果有两个或更多的最大值,我希望在地图中首先出现的键,在本例中为Manoj。在我的应用程序中,我使用了Collections.max(map.getKey()),它返回Rahul创建一个比较器,该比较器按值降序排序条目,然后在两个值相等时按键比较 Entry.<String, Integer>comparingByValue().r

我有一个
TreeMap
,其中包含如下条目

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

我希望获得具有最大值的键,但是如果有两个或更多的最大值,我希望在地图中首先出现的键,在本例中为
Manoj
。在我的应用程序中,我使用了
Collections.max(map.getKey())
,它返回
Rahul

创建一个比较器,该比较器按值降序排序条目,然后在两个值相等时按键比较

Entry.<String, Integer>comparingByValue().reversed()
.thenComparing(Entry.comparingByKey())

创建一个
比较器
并将其传递给
Collections.max()

Map Map=newtreemap(
地图(“Aftab”,4,“Manoj”,5,“Rahul”,5));
Comparator comp=Entry.comparingByValue();
条目e=Collections.max(map.entrySet(),comp);
系统输出打印ln(e);
//或
System.out.println(e.getKey());

使用
Collections::max
通过使用
Comparator.comparingit(map.entry::getValue)
map.entrySet()
中查找具有最大值的条目

演示:
这回答了你的问题吗?是的,这是一个正确的答案。是的@Arvind Kumar Avinash,你的答案绝对正确。这个答案也是正确的,但对我来说有点复杂。它应该只打印“manoj”。
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
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());
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