根据参数值和低于它的值获取hashmap键

基本上我想用用户给定的值迭代哈希图,但也包括任何具有键的较小值“价格”。具有键的可能值为 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);

                }

            }

        }

    } 


浮云间
浏览 68回答 1
1回答

慕尼黑的夜晚无繁华

您的代码的问题在于您将搜索值本身如下所示:bestPrices.put(entry.getKey(),&nbsp;value);相反,您必须按如下方式输入条目的值:bestPrices.put(entry.getKey(),&nbsp;entry.getValue());
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java