【问题标题】:How do I get key based on some specific condition from values in a HashMap in Java?如何根据某些特定条件从 Java HashMap 中的值获取密钥?
【发布时间】:2021-09-21 20:56:42
【问题描述】:

我想要一个基于值的特定条件的 HashMap 中的特定键。例如: 我的 HashMap 的类型是 <String,Integer>

Map<String,Integer> getValuesInMap = new HashMap<String,Integer>(); 
Output = {Python=1, Java=1, OOPS=2, language=1, Ruby=3, Hey=1}

我想从这个映射中检索整数计数(即值)大于 1 的键。

【问题讨论】:

    标签: java collections hashmap


    【解决方案1】:

    HashMap 不适用于此类操作,因此您可以手动执行,也可以使用Stream

    getValuesInMap.entrySet()
      .stream()
      .filter(e -> e.getValue() >  1)
      .map(e -> e.getKey())
      .collect(Collectors.toList());
    

    【讨论】:

      【解决方案2】:

      如果您使用的 Java 大于 1.7,则可以使用 streams,如下所示

      Map<String,Integer> map = new HashMap<>();
          map.put("Python", 1);
          map.put("Java", 1);
          map.put("OOPS", 2);
          map.put("Language", 1);
          map.put("Ruby", 3);
          map.put("Hey", 1);
      
          List<String> collect = map.entrySet().stream()
                  .filter(entry -> entry.getValue() > 1)
                  .map(entry -> entry.getKey())
                  .collect(Collectors.toList());
          System.out.println(collect);
      

      【讨论】:

        【解决方案3】:

        在地图的值上使用Collection.removeIf

        getValuesInMap.values().removeIf(count -> count <= 0);
        System.out.println(getValuesInMap);
        

        请注意,上述内容实际上会从您的地图中删除条目。如果您需要保留原始地图,请制作一份副本:

        Map<String, Integer> copy = new LinkedHashMap<>(getValuesInMap);
        copy.values().removeIf(count -> count <= 0);
        System.out.println(copy);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-06-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-09-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多