查找与Java Map中的最大值关联的密钥

Ben*_* B. 125 java hashmap

获取地图中最大值关键字的最简单方法是什么?

我相信当您需要与最大值对应的键时,Collections.max(someMap)将返回最大键.

Jon*_*eet 124

基本上你需要迭代地图的入口集,记住"当前已知的最大值"和与之关联的密钥.(当然,或者仅包含两者的条目.)

例如:

Map.Entry<Foo, Bar> maxEntry = null;

for (Map.Entry<Foo, Bar> entry : map.entrySet())
{
    if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0)
    {
        maxEntry = entry;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • +1:您可以拥有多个具有相同最大值的密钥.这个循环将为您找到它找到的第一个. (34认同)
  • 将> 0更改为> = 0将为您找到它找到的最后一个 (18认同)
  • @zkarthik:使用`max`和自定义比较器可能会更简单. (2认同)

Hil*_*kus 95

为了完整起见,这是一种方式

countMap.entrySet().stream().max((entry1, entry2) -> entry1.getValue() > entry2.getValue() ? 1 : -1).get().getKey();
Run Code Online (Sandbox Code Playgroud)

要么

Collections.max(countMap.entrySet(), (entry1, entry2) -> entry1.getValue() - entry2.getValue()).getKey();
Run Code Online (Sandbox Code Playgroud)

要么

Collections.max(countMap.entrySet(), Comparator.comparingInt(Map.Entry::getValue)).getKey();
Run Code Online (Sandbox Code Playgroud)

  • 如果我想要所有与最大值匹配的键怎么办? (5认同)
  • `(entry1,entry2) - > entry1.getValue() - entry2.getValue()`比较器更紧凑. (3认同)
  • 或者你可以使用`Map.Entry.comparingByValue()`代替 (3认同)
  • 紧凑但难以理解. (2认同)

Fat*_*n P 50

此代码将打印具有最大值的所有键

public class NewClass4 {
    public static void main(String[] args)
    {
        HashMap<Integer,Integer>map=new HashMap<Integer, Integer>();
        map.put(1, 50);
        map.put(2, 60);
        map.put(3, 30);
        map.put(4, 60);
        map.put(5, 60);
        int maxValueInMap=(Collections.max(map.values()));  // This will return max value in the Hashmap
        for (Entry<Integer, Integer> entry : map.entrySet()) {  // Itrate through hashmap
            if (entry.getValue()==maxValueInMap) {
                System.out.println(entry.getKey());     // Print the key with max value
            }
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

  • 它应该是“Map.Entry&lt;Integer, Integer&gt; 条目:valmap.entrySet()” (2认同)

Sle*_*idi 40

使用Java-8的简单单线程

Key key = Collections.max(map.entrySet(), Map.Entry.comparingByValue()).getKey();
Run Code Online (Sandbox Code Playgroud)

  • @Samir https://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html#getKey() (3认同)
  • 最优雅,最小化的解决方案.谢谢 (3认同)
  • 不起作用,找不到getKey()方法 (2认同)
  • 如果这样的键最多有 2 个怎么办?它如何返回这样的键值的数组? (2认同)
  • @SleimanJneidi 这个问题没有询问重复的键。考虑这样的情况:- &lt;1,8&gt; &lt;2,8&gt; &lt;5,4&gt; &lt;4,6&gt; &lt;6,7&gt; 有 2 个键的最大值为 8。因此它应该返回 1,2。 (2认同)

Ami*_*mir 8

以下是如何通过定义适当的方法直接(没有明确的额外循环)来做到这一点Comparator:

int keyOfMaxValue = Collections.max(
                        yourMap.entrySet(), 
                        new Comparator<Entry<Double,Integer>>(){
                            @Override
                            public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
                                return o1.getValue() > o2.getValue()? 1:-1;
                            }
                        }).getKey();
Run Code Online (Sandbox Code Playgroud)


Man*_*tra 7

1. 使用流

public <K, V extends Comparable<V>> V maxUsingStreamAndLambda(Map<K, V> map) {
    Optional<Entry<K, V>> maxEntry = map.entrySet()
        .stream()
        .max((Entry<K, V> e1, Entry<K, V> e2) -> e1.getValue()
            .compareTo(e2.getValue())
        );
     
    return maxEntry.get().getKey();
}
Run Code Online (Sandbox Code Playgroud)

2. 使用 Collections.max() 和 Lambda 表达式

    public <K, V extends Comparable<V>> V maxUsingCollectionsMaxAndLambda(Map<K, V> map) {
        Entry<K, V> maxEntry = Collections.max(map.entrySet(), (Entry<K, V> e1, Entry<K, V> e2) -> e1.getValue()
            .compareTo(e2.getValue()));
        return maxEntry.getKey();
    }
Run Code Online (Sandbox Code Playgroud)

3. 使用带有方法引用的流

    public <K, V extends Comparable<V>> V maxUsingStreamAndMethodReference(Map<K, V> map) {
        Optional<Entry<K, V>> maxEntry = map.entrySet()
            .stream()
            .max(Map.Entry.comparingByValue());
        return maxEntry.get()
            .getKey();
    }
Run Code Online (Sandbox Code Playgroud)

4. 使用 Collections.max()

    public <K, V extends Comparable<V>> V maxUsingCollectionsMax(Map<K, V> map) {
        Entry<K, V> maxEntry = Collections.max(map.entrySet(), new Comparator<Entry<K, V>>() {
            public int compare(Entry<K, V> e1, Entry<K, V> e2) {
                return e1.getValue()
                    .compareTo(e2.getValue());
            }
        });
        return maxEntry.getKey();
    }
Run Code Online (Sandbox Code Playgroud)

5. 使用简单迭代

public <K, V extends Comparable<V>> V maxUsingIteration(Map<K, V> map) {
    Map.Entry<K, V> maxEntry = null;
    for (Map.Entry<K, V> entry : map.entrySet()) {
        if (maxEntry == null || entry.getValue()
            .compareTo(maxEntry.getValue()) > 0) {
            maxEntry = entry;
        }
    }
    return maxEntry.getKey();
}
Run Code Online (Sandbox Code Playgroud)

  • `3. 将 Stream 与 Method Reference 一起使用非常酷。 (2认同)

Dav*_* L. 6

返回Optional的答案,因为如果映射为空,则映射可能没有最大值: map.entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey);


Jor*_*sys 6

我有两种方法,使用这种方法来获取具有最大值的键:

 public static Entry<String, Integer> getMaxEntry(Map<String, Integer> map){        
    Entry<String, Integer> maxEntry = null;
    Integer max = Collections.max(map.values());

    for(Entry<String, Integer> entry : map.entrySet()) {
        Integer value = entry.getValue();
        if(null != value && max == value) {
            maxEntry = entry;
        }
    }
    return maxEntry;
}
Run Code Online (Sandbox Code Playgroud)

例如,使用以下方法获取具有最大值的条目:

  Map.Entry<String, Integer> maxEntry =  getMaxEntry(map);
Run Code Online (Sandbox Code Playgroud)

使用Java 8我们可以得到一个包含最大值的对象:

Object maxEntry = Collections.max(map.entrySet(), Map.Entry.comparingByValue()).getKey();      

System.out.println("maxEntry = " + maxEntry);
Run Code Online (Sandbox Code Playgroud)


小智 5

简单易懂。在下面的代码中,maxKey 是保存最大值的键。

int maxKey = 0;
int maxValue = 0;
for(int i : birds.keySet())
{
    if(birds.get(i) > maxValue)
    {
        maxKey = i;
        maxValue = birds.get(i);
    }
}
Run Code Online (Sandbox Code Playgroud)