【问题标题】:Getting hashmap keys based on parameter value and values lower than it根据参数值和低于它的值获取 hashmap 键
【发布时间】:2020-02-16 10:22:21
【问题描述】:

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

【问题讨论】:

  • “打印”是什么意思?那里没有打印任何东西
  • 您的代码看起来不错。当您尝试使用值 (1250,900,600,300) 和 600 作为输入时,bestPrices 地图将只包含 600 而不是 300?

标签: java arrays hashmap


【解决方案1】:

您的代码的问题在于您将搜索值本身如下:

bestPrices.put(entry.getKey(), value);

相反,您必须按如下方式输入条目的值:

bestPrices.put(entry.getKey(), entry.getValue());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-16
    • 1970-01-01
    • 1970-01-01
    • 2010-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-15
    相关资源
    最近更新 更多