java - 改变HashMap键的具体值

标签 java hashmap key-value

我有 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)", 0);
    species.put("eagle (aquila chrysaetos)", 0);
    species.put("sparrow (passeridae)", 0);

    System.out.println("Add perception");
    System.out.println("What was perceived?"); //output should be "hawk"/"eagle"/"sparrow"
    String perception = reader.nextLine();

    // Change here the value of hashmap key.

    ArrayList<String> list = new ArrayList<>();
    for (HashMap.Entry<String, Integer> entry: species.entrySet()) {
        System.out.println((entry.getKey()+" : "+entry.getValue()+" perception"));
    }



}

我的目标是当扫描仪询问感知到的内容时,将键值从 0 更改为 1。

例如: 扫描仪询问“感知到了什么?”输出是“hawk”。然后程序应该将键“hawk (buteo jamaicensis)”值从 0 更改为 1。因此目标输出现在是:

sparrow (passeridae) : 0 perception
eagle (aquila chrysaetos) : 0 perception
hawk (buteo jamaicensis) : 1 perception

最佳答案

使用String.indexOf检查输入字符串是否是该键的子字符串,如果是,则设置新值:

// Change here the value of hashmap key.
for (HashMap.Entry<String, Integer> entry: species.entrySet()) {
    if (entry.getKey().indexOf(perception) >= 0) {
        entry.setValue(entry.getValue() + 1);
}

关于java - 改变HashMap键的具体值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49275295/

相关文章:

java - 具有来自 List<List<String>> 的频率计数的唯一值

android - Kotlin 中的方法 hashMapOf()

java - 了解 HashMap 和 IdentityHashMap

Python:从value中获取对应的key

java - TreeMap[A,B] 上的双向迭代器

java - 在java中将元素推送到Vector

java - 如何将 CXF 客户端的 TLS/SSL Http 身份验证用于 Web 服务?

java - 防止Java类被实例化和继承

javascript - 从 web.config 读取键值时,aspx 页面中的标识符预期出现错误 javascript

java - 收集可能为空的值