【问题标题】:How to compare values in a map with a threshold and put the values greater than the minimum threshold in a set如何将地图中的值与阈值进行比较并将大于最小阈值的值放入集合中
【发布时间】:2019-09-23 05:28:27
【问题描述】:

我有一个包含字符串键和整数值的映射,我试图将这些值与阈值(例如 40)进行比较,并将所有值大于阈值的键打印到一组中。这是我的代码和我得到的错误。我是java新手

    int m = 40;

    Set<Map.Entry<String, Integer>> set = map.entrySet();


    System.out.println();
    Iterator<Map.Entry<String, Integer>> i = set.iterator();

    while (i.hasNext() ) { 
        Map.Entry e = i.next(); 

    if(e.getValue() > m) { 
        set.add(e.getKey());
    }
    System.out.println("Set of local file names and malware score : "+ i.next()); 
    }

错误:

no suitable method found for add(Object)
                        set.add(e.getKey());
                           ^
    method Collection.add(Entry<String,Integer>) is not applicable
      (argument mismatch; Object cannot be converted to Entry<String,Integer>)
    method Set.add(Entry<String,Integer>) is not applicable
      (argument mismatch; Object cannot be converted to Entry<String,Integer>)
2 errors

【问题讨论】:

    标签: java


    【解决方案1】:

    您正在尝试将键(String 类型)添加到条目 Set(其中包含 Map.Entry&lt;String,Integer&gt; 类型的元素)。这就是错误的原因。

    但是,即使类型匹配,您也不应该修改 Map 的条目 Set(除非您也想修改底层 Map)。

    您应该创建一个单独的Set 来存储相关密钥:

    Set<String> set = new HashSet<>();
    
    System.out.println();
    Iterator<Map.Entry<String, Integer>> i = map.entrySet().iterator();
    
    while (i.hasNext() ) { 
        Map.Entry<String,Integer> e = i.next(); 
    
        if(e.getValue() > m) { 
            set.add(e.getKey());
        }
    }
    

    我从循环中删除了您的 println 语句,因为它在同一迭代中第二次推进 Iterator,这是错误的。

    【讨论】:

      猜你喜欢
      • 2017-08-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      • 1970-01-01
      • 2020-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多