基本上我想用用戶給定的值迭代哈希圖,但也包括任何具有鍵的較小值“價格”。具有鍵的可能值為 1250、900、600、300。例如,如果用戶輸入 600,但有值 300 的鍵,則打印 600 和 300 值的所有鍵。這是我到目前為止所擁有的,但它只會打印給出的初始值的鍵,而不是較低的值。 private Map<Integer, Integer> prices = new HashMap<>(); private Map<Integer, Integer> bestPrices = new HashMap<>(); public void findBestPrice(LithiumPricing obj, Integer value) { //get hashmap prices from class LithiumPricing. prices = obj.getPrices(); bestPrices.clear(); if (prices.containsValue(value)){ for (Map.Entry<Integer, Integer> entry : prices.entrySet()) { if (entry.getValue() <= value){ bestPrices.put(entry.getKey(), value); } } } }
1 回答

慕尼黑的夜晚無繁華
TA貢獻1864條經驗 獲得超6個贊
您的代碼的問題在于您將搜索值本身如下所示:
bestPrices.put(entry.getKey(), value);
相反,您必須按如下方式輸入條目的值:
bestPrices.put(entry.getKey(), entry.getValue());
添加回答
舉報
0/150
提交
取消