使用 Java 8 迭代 Map<String,Object> 数组并返回 Map<Long,Long>

Ros*_*han 2 java lambda java-8 java-stream

我有一个地图数组。其中我需要做一些计算并返回另一个 Map 并将相同的键计数添加到结果中的值中。我试过下面的一个。但由于它是并行运行的,因此不会添加它。

请帮助改进它

我可以在正常的 for 循环中实现这一点。

public Map<Long,Long> solve(Map<String,Stats>... map){
        Map<Long,Long> resultCount = new HashMap<Long,Long>();
        if(map != null){
       
            resultCount = Arrays.stream(map).filter(Objects::nonNull).map(map -> getUserCountMap(map))
            .collect(HashMap::new, Map::putAll, Map::putAll);
  
    }
        return resultCount;
    }
    
   public Map<Long,Long>  getUserCountMap(Map<String, Stats> map) {
       Map<Long,Long> resultCount = new HashMap<Long,Long>();
       
       map.forEach((k,v)->{
           try {
                
               String key = (String) k;
               Stats userValue = (Stats) v;
               Long userId = new Long(key);
               System.out.println("key :::"+key+":::"+resultCount.getOrDefault(userId, 0l));
               Optional<Long> count = userValue.getCount();
               System.out.println(count.get());
               count.ifPresent(aLong -> resultCount.put(userId, (resultCount.getOrDefault(userId, 0l) + aLong)));
               System.out.println(resultCount);

           } catch (Exception e) {
           } 
       }
       );
       
       System.out.println("ret "+resultCount);
           return resultCount;
       
   }
Run Code Online (Sandbox Code Playgroud)

任何了解 Java 8 Streams API 和各种中间和终端操作的好文档

Era*_*ran 6

您没有使用正确的收集器。

您可以使用Collectors.toMap合并函数来添加相同键的值。

但首先我建议您将所有s的所有条目中的Stream<Map<>>a转换为 a 。Stream<Map.Entry<>>Map

  resultCount = 
      Arrays.stream(map)
            .filter(Objects::nonNull)
            .flatMap(map -> getUserCountMap(map).entrySet().stream())
            .collect(Collectors.toMap(Map.Entry::getKey,
                                      Map.Entry::getValue,
                                      (v1,v2)->v1+v2));
Run Code Online (Sandbox Code Playgroud)

试图摆脱 getUserCountMap:

  resultCount = 
      Arrays.stream(map)
            .filter(Objects::nonNull)
            .flatMap(map -> map.entrySet().stream())
            .map(e -> new SimpleEntry<Long,Long>(Long.valueOf(e.getKey()),e.getValue().getCount().orElse(0L)))
            .collect(Collectors.toMap(Map.Entry::getKey,
                                      Map.Entry::getValue,
                                      (v1,v2)->v1+v2));
Run Code Online (Sandbox Code Playgroud)

我不确定后者是否完全等同于您的getUserCountMap逻辑。