簡體   English   中英

Java:在HashMap中獲取2個最高值的索引

[英]Java: Getting index of 2 highest values in HashMap

以下代碼返回前2個最大值的相同索引:

HashMap<Integer, Integer> S_List = new HashMap<Integer, Integer>();

    S_List.put(3, 18);
    S_List.put(9, 20);
    S_List.put(11,20);
    S_List.put(13,20);
    S_List.put(15,20);
    S_List.put(17,20);
    S_List.put(19,20);

    Map.Entry<Integer, Integer> maxEntry5 = null;
    Map.Entry<Integer, Integer> maxEntry6 = null;

    for (Map.Entry<Integer, Integer> entry : S_List.entrySet())
    {
        if (maxEntry5 == null || entry.getValue() > maxEntry5.getValue())
        {
            maxEntry5 = entry;
        }
        if (maxEntry6 == null || entry.getValue() > maxEntry6.getValue()
                  && entry.getKey() != maxEntry5.getKey()) {
            maxEntry6 = entry;
        } 
    }

Entry5和Entry6的輸出均為17 = 20,但應為不同的索引。

還有一個附帶的問題,當所有值均為20時,我如何才能為前2個值獲得2個隨機索引。

應該使用等號比較對象。

 if (maxEntry6 == null || entry.getValue() > maxEntry6.getValue()
              && ! entry.getKey().equals( maxEntry5.getKey())) {
        maxEntry6 = entry;
 }

但是主要的問題是邏輯:

if (maxEntry6 == null || 
       entry.getValue() >= maxEntry6.getValue()
    && ! entry.getKey().equals( maxEntry5.getKey())) {
        maxEntry6 = entry;
    } 

即使值相等,您也需要另一個鍵的值。

如果出現以下情況,則更簡單的解決方案是:

   if (maxEntry5 == null ||
       entry.getValue() >= maxEntry5.getValue()) {
        maxEntry6 = maxEntry5;
        maxEntry5 = entry;
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM