簡體   English   中英

從鍵迭代LinkedHashMap值

[英]Iterating LinkedHashMap values from the key

我正在努力處理一些代碼,但是我無法弄清楚正確的語法是什么。 這是問題的示例:

for (Integer key : map1.keySet()) {

    for (Integer value : map2.values()) {

        if (value == key) {

            // ++ the corresponding value of the looping map1 key.
            // tried statements like map1.values()++  
            // but this is an invalid operation.

        }
    }
}

我正在嘗試通過map2值循環map1鍵,如果在此過程中map1鍵與map2值匹配,我想在對應map1鍵的值上加一個。

應該是一個簡單的問題,但是Eclipse不斷告訴我語法錯誤,有人可以建議我可能需要迭代哪些語句嗎?

這是對代碼進行很小的修改即可實現的方法:

for (Map.Entry<Integer,Integer> entry : map1.entrySet()) {
    for (Integer value : map2.values()) {
        if (value.equals(entry.getKey())) {
            entry.setValue(entry.getValue()+1);
        }
    }
}

編輯:由於map2可能多次包含相同的 ,因此使用哈希集加快處理速度的其他解決方案將無法按預期工作。

我不確定為什么Eclipse報告語法錯誤,但是無論如何,此循環沒有多大意義,請考慮將其更改為:

for (Integer value : map2.values())
    if (map1.containsKey(value))
        // bla bla

它將在O(n)中運行,而不是前一個O(n * m)

當n是map2的大小而m是map1的大小時(由@dasblinkenlight通知)

您如何初始化地圖? 類似於Map<Integer, Integer> map1=new LinkedHashMap<Integer, Integer>(); Map map1=new LinkedHashMap(); 如果采用第二種方式,則密鑰將為“ Object not Integer”。 並且在所有情況下都使用==不好的做法比較兩個Integer。 使用等於

您可以使用containsKey方法,如下所示:

for (Integer value : map2.values()){
if (map1.containsKey(value))
    map1.put(key, value);

...
}

暫無
暫無

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

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