2016-09-21 74 views
-3
Map<Integer, Integer> listInfo = new HashMap<Integer, Integer>(); 

我一直在試圖從谷歌搜索,但我不知道爲什麼我找不到正確的解決方案。無論如何,我的HashMap將存儲兩個整數。我會使用普通的「int []」字符串列表或任何它被調用,但它會返回異常的事情有關「數組outofbounds」或相關的東西,因爲它的索引將比int大。不確定,但無論如何,讓我們留在話題中。JAVA - HashMap檢查特定的鍵值(如果更大)

我的英語很糟糕,但如果你不明白我在說什麼,希望這會有所幫助。 (只是想法,不是基於真正的代碼)

if(listInfo.containsKey(key)) { 
    if(listInfo.getKeyValue(key).valueOfKey() > valueToBeAdded) { 
     listInfo.put(key, valueToBeAdded); 
    } 
} else { 
    listInfo.put(key, valueToBeAdded); 
} 

我都試過比上述類似的方式,但非常正確的功能,但它會產生衝突,因爲它說,它不能比較鍵值int,因爲鍵值是對象嗎?爲什麼它是對象,因爲我已經定義它應該是整數?我也嘗試過(Entry entry:......)循環,但我不知道如何獲得特定鍵的值(我不是在談論鍵值,我正在談論的是特定鍵的值持有)

我只想更新特定(現有)鍵所保持的值,如果該鍵所保存的值較大並且要添加的值小於當前值。

+0

向我們展示您的代碼,我們無法猜測您做錯了什麼。 – Shadov

+0

和確切的錯誤。請[編輯]問題,並粘貼代碼和錯誤。不要忘記用'{}'按鈕來設置它們的格式。 – RealSkeptic

+0

瞬間。我會添加它。 –

回答

1

在下面找到一個你正在尋找的代碼片段(假設我理解你的意圖)。

Map<Integer, Integer> listInfo = new HashMap<>(); 
listInfo.put(1, 23); 
listInfo.put(2, 45); 
Integer valueToBeAdded = 42; 
System.out.println("listInfo = " + listInfo); 
if (listInfo.containsKey(1)) { 
    if (listInfo.get(1) < valueToBeAdded) { 
     listInfo.put(1, valueToBeAdded); 
    } 
} else { 
    listInfo.put(1, valueToBeAdded); 
} 
System.out.println("listInfo = " + listInfo); 

輸出

listInfo = {1=23, 2=45} // the initial listInfo entries (key, value) 
listInfo = {1=42, 2=45} // after the value for key `1` has been updated 
+0

我剛剛要添加代碼,但在此之前必須做更多的調試,但實際上在第6-9行獲得瞭解決方案。我不認真瞭解是什麼導致了這個錯誤,因爲我在發佈後立即清理了太多的代碼。但工作得很好O_o我很頭疼。謝謝。 –

0

看起來你只想把那個較小值。
爲此,您可以使用Map.compute

final HashMap<Integer, Integer> map = new HashMap<Integer,Integer>(); 
map.put(123, 456); 
System.out.println(map); 
final int x = 234; 
final BiFunction<? super Integer, ? super Integer, ? extends Integer> f = 
    (k, v) -> v == null ? x : Math.min(v, x); 
map.compute(123, f); 
map.compute(999, f); 
System.out.println(map); 

可悲的是,Java不支持真正的函數式編程。有一個簡單的部分應用程序將是很好的。 這是一個靜態方法的版本,部分應用某個值並返回一個BiFunctionf是一個更高階的函數)。

public static void main(final String[] arrg) { 
    final HashMap<Integer, Integer> map = new HashMap<Integer,Integer>(); 
    map.put(123, 456); 
    System.out.println(map); 
    map.compute(123, f(345)); 
    map.compute(123, f(99999)); 
    map.compute(999, f(888)); 
    System.out.println(map); 
    } 

    static BiFunction<? super Integer, ? super Integer, ? extends Integer> f(final int x) { 
    return (k, v) -> v == null ? x : Math.min(v, x); 
    }