【问题标题】:Check if the key value exists in hashmap [closed]检查哈希图中是否存在键值[关闭]
【发布时间】:2018-03-14 19:31:27
【问题描述】:

我有 HashMap,其中键是鸟类,值是感知的数量。这是我的代码:

public class Program {

public static void main(String[] args) {

    HashMap<String, Integer> species = new HashMap<>();
    Scanner reader = new Scanner(System.in);

    species.put("hawk (buteo jamaicensis)", 2);
    species.put("eagle (aquila chrysaetos)", 4);
    species.put("sparrow (passeridae)", 5);

    System.out.println("What specie?"); //output "chicken"
    String specie = reader.nextLine();

    for (HashMap.Entry<String, Integer> entry: species.entrySet()) {
        if (entry.getKey().contains(specie)) {
            System.out.println(entry.getKey()+" : "+entry.getValue()+" perceptions");
        } else {
            System.out.println("Not in database!");
        }
    } 
}

}

如何检查该物种是否存在于 hashmap 中?例如,如果物种输出是“鸡”并且它不在数据库中,那么程序应该打印“不在数据库中!”。现在的输出是:

Not in database!
Not in database!
Not in database!

我的目标输出是:

Not in database!

【问题讨论】:

  • 当你可以调用containsKey时,你为什么要遍历HashMap的所有条目?
  • 你在哪里看到“鸡”:species.put("hawk (buteo jamaicensis)", 2); species.put("eagle (aquila chrysaetos)", 4); species.put("sparrow (passeridae)", 5);
  • @davidxxx 这就是为什么预期的输出是“不在数据库中!”
  • 许多人似乎忽略了这样一个事实,即 OP 正在(似乎是有意地)检查每个字符串键是否包含输入字符串,而不仅仅是检查它们是否相等。
  • 您应该重新考虑:对您的哈希映射的访问是否必须使用全名(通用英语加拉丁语),或者只是通用名称,或者只是拉丁名称?您可能希望将英文名称和拉丁名称都映射到一个 Bird 对象,您可以在其中将两个术语(可能更多)保留为字段。

标签: java for-loop hashmap


【解决方案1】:

为此使用布尔标志:

boolean found = false;
for (HashMap.Entry<String, Integer> entry: species.entrySet()) {
        if (entry.getKey().contains(specie)) {
            System.out.println(entry.getKey()+" : "+entry.getValue()+" perceptions");
            found = true;
        }
} //Loop ends
if (!found) {
        System.out.println("Not in database!");
}

【讨论】:

    【解决方案2】:

    您也可以为此使用Java 8 Streams:(尽管我可能只是推荐使用 for 循环)

    Optional<Map.Entry<String, Integer>> match = 
          species.entrySet().stream().filter(entry -> entry.getKey().contains(specie)).findAny();
    if (match.isPresent())
       System.out.println(match.get().getKey()+" : "+match.get().getValue()+" perceptions");
    else
       System.out.println("Not in database!");
    

    .stream 将条目集转换为流。
    .filter 删除我们要查找的元素以外的所有元素。
    .findAny 如果存在元素,则返回一个元素。


    虽然,如果您通过 Map 循环查找您要查找的内容,这会破坏 Map 的用途,您可能希望选择某个自定义类的 List,将 String 拆分为 2然后将键设为通用英文名称(如 cmets 中推荐的 laune)或使用更复杂的数据结构,以实现高效的子字符串查找,如 suffix tree

    【讨论】:

      【解决方案3】:

      我认为流媒体对此有点过头了。

      if(species.containsKey(selectedSpecie)) {
         return species.get(selectedSpecie);
      } else {
        throw new IllegalStateException("Not in database!");
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-05
        • 2016-06-30
        • 2013-02-18
        • 2011-05-19
        • 2017-06-10
        • 2011-05-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多