java - 如何根据先验条件更新 HashMap 中的值?

标签 java hashmap

关于 HashMap 和 for 循环的一些基本知识对我来说很难理解。我想做的是每次数组列表中的值与键字符串关联时,根据 Keys 方法将 +1 添加到与键关联的值。

因此,如果数组列表中有 3 个值为正的值,则 HashMap 应将键为“正”的值更新为 3。

任何帮助/建议将不胜感激 - 谢谢。

public String Keys(double input){

    if (input > 0){
        System.out.println("positive");
    }
    else if (input < 0) {
        System.out.println("negative");
    }
    else if (input == 0) {
        System.out.println("zero");
    }
    return "";
}

public HashMap<String, Integer> increaseValues(ArrayList<Double> inputs){
    HashMap<String, Integer> hashMap = new HashMap<>();
    hashMap.put("positive", 0);
    hashMap.put("negative", 0);
    hashMap.put("zero", 0);

//What I tried before adding the Keys method.
//This updates the value but the loop won't continue if another input in the 
//arraylist is true.

for (int i = 0; i < inputs.size(); i++){
        double input = inputs.get(i);

        if (input > 0){
           hashMap.put("positive", 1);
        } else if (input < 0){
          hashMap.put("negative", 1);
        } else if (input == 0){
          hashMap.put("zero", 1); }
    return hashMap;
}

public void main(String[] args){
    ArrayList<Double> inputs = new ArrayList<>();
    inputs.add(-4.56);
    inputs.add(-4.66);
    inputs.add(0.0);
    inputs.add(6.0);
    inputs.add(-6.99);
    inputs.add(6.97);   
}

最佳答案

Map.put(k, v) 始终覆盖您之前的值。您可以使用“传统方法”:

if (!map.containsKey("positive"))
    map.put("positive", 0);
map.put("positive", map.get("positive") + 1);

或者更好地使用针对此类情况添加的新merge 函数:

map.merge("positive", 1, (prev, one) -> prev + one);

但是通过使用 Math.signum() 和流收集器可以大大缩短整个逻辑:

Map<Double, Long> collect = inputs.stream()
                                  .collect(Collectors.groupingBy(Math::signum,
                                                                 Collectors.counting()));
System.out.println("positive: " + collect.get(1.0));
System.out.println("negative: " + collect.get(-1.0));
System.out.println("zero: " + collect.get(0.0));

关于java - 如何根据先验条件更新 HashMap 中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50094619/

相关文章:

java - 如何允许在此 Java 代码中检查两个以上的单词

可以通过 GUI 和命令行控制的 Javafx 程序?

java - 查询请求: EC2 Version

java - HashMap put() api 时间复杂度

java - 在 Java 中返回一个可迭代列表

javascript - 使用数组作为哈希表

hashtable - 开放寻址与分离链接

java - 打印机驱动程序在java中的实现

java - JSoup 按 id 提取文本

Java 命令行应用程序以某种方式保留状态