【发布时间】:2019-12-13 06:33:16
【问题描述】:
我的parentMap 如下所示。
HashMap<String, Integer>>> parentMap = {disabled={account={test1=22}, group={test2=10}}}
我想做的是,如果operationType=disabled 和objectType=account 或group 等和testName=test1 或test2 等,那么我想将test1 的计数增加1。
我必须更新同一张地图,以便最后我应该得到一些统计数据,比如有 22 个 tests 案例 objectType=account 和 10 个 tests 案例 objectType=group 等被禁用
我在下面尝试了一些方法,但它进入了无限循环,因为我将值放入地图并再次对其进行迭代。
private HashMap<String, HashMap<String, HashMap<String, Integer>>> countTags(String statType, String objectType,
String opType, HashMap<String, HashMap<String, HashMap<String, Integer>>> parentMap) {
if (!Util.isEmpty(parentMap)) {
//created new map to avoid infinite loop here but no luck :(
HashMap<String, HashMap<String, Integer>> objMap = new HashMap<>();
objMap.putAll(parentMap.get(statType));
Iterator<Entry<String, HashMap<String, Integer>>> it = objMap.entrySet().iterator();
while (it.hasNext()) {
Entry<String, HashMap<String, Integer>> operationEntry = it.next();
HashMap<String, Integer> operationMap = operationEntry.getValue();
Set<String> opKeySet = operationMap.keySet();
Iterator<String> opIt = opKeySet.iterator();
while (opIt.hasNext()) {
parentMap.put(statType, countTags(objectType, opType, operationMap));
}
}
} else {
parentMap.put(statType, countTags(objectType, opType, new HashMap<String, Integer>()));
}
return parentMap;
}
private HashMap<String, HashMap<String, Integer>> countTags(String objectType, String opType, HashMap<String, Integer> tagMap) {
int testRepeatCount = tagMap.get(opType) != null ? tagMap.get(opType) : 0;
tagMap.put(opType, 1 + testRepeatCount);
HashMap<String, HashMap<String, Integer>> objMap = new HashMap<>();
objMap.put(objectType, tagMap);
return objMap;
}
我发现
a.compute(key, (k, v) -> v == null ? 1 : v + 1); 也有一些建议 Java map.get(key) - automatically do put(key) and return if key doesn't exist? 但我可以得到一些帮助,我应该如何在这里以最佳方式实现我想要的结果?
【问题讨论】:
-
是的,你从不打电话给
opIt.next() -
我明白了。像
parentMap.computeIfPresent("disable", (k, v) -> v + 1)这样的事情会帮助我吗????? -
不知道,但不会删除无限循环
while (opIt.hasNext()) -
在你的第一个代码 sn-ps 中,右尖括号是不平衡的。
标签: java data-structures collections recursive-datastructures