我有一个 map 数组。我需要在其中进行一些计算并返回 Another 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;
}
任何了解 Java 8 Streams API 和各种中间和终端操作的好文档
最佳答案
您没有使用正确的收集器。
您可以使用 Collectors.toMap
具有合并功能,可以添加相同键的值。
但首先我建议你转换你的 Stream<Map<>>
到 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));
尝试摆脱 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));
我不确定后者是否完全等同于您的 getUserCountMap
逻辑。
关于java - 使用 Java 8 迭代 Map<String,Object> 数组并返回 Map<Long,Long>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66686574/