代码之家  ›  专栏  ›  技术社区  ›  upog

流迭代hashMap并处理数据

  •  0
  • upog  · 技术社区  · 5 年前

    我想使用java Stream迭代hashmap,并为每个键执行一个内联函数 然后求和该值

    Map<Integer, Integer>  myMap= new HashMap<Integer, Integer>() {{ 
                    put(5000, 0);
                    put(1000, 10);
                }};
    
    myMap.entrySet().stream().map(e-> {/* want to fetch the corresponding value and increment by X  and find the sum*/ });
    
    2 回复  |  直到 5 年前
        1
  •  3
  •   pvpkiran    5 年前

    试试这个。这应该行得通。

    final Integer sum = myMap.values()
                             .stream()
                             .map(value-> value + X)
                             .reduce(0, Integer::sum)
    

    i如果您想访问密钥,请尝试以下操作

    myMap.entrySet()
                    .stream()
                    .map(entry -> entry.getValue() + X) // you can use entry.getKey() to get access to key
                    .reduce(0, Integer::sum);
    
        2
  •  1
  •   Thiyagu    5 年前

    使用 mapToInt 生成一个 IntStream sum 以对映射的元素求和。

    myMap.entrySet()
       .stream()
       .mapToInt(entry -> entry.getValue() + X)
       .sum();