这是关于 Java 的,但为了便于阅读,我将使用 JSON 编写示例。
假设我有一个 List
的 Map
设置如下:
[{
"id": 1,
"foo": 12,
"bar": 34
}, {
"id": 1,
"baz": 56
}, {
"id": 2,
"foo": 78
}, {
"id": 2,
"bar": 90
}]
我想做的是合并具有相同 id
的 map 。基本上,我想以这样的方式结束:
[{
"id": 1,
"foo": 12,
"bar": 34,
"baz": 56
}, {
"id": 2,
"foo": 78,
"bar": 90
}]
我发现的所有其他问题都涉及以不相关的方式合并 map ,并且大多数只关心两个 map ,而不是可变数量。
这段代码似乎可以工作,但让我觉得有点冗长:
List<Map<String, Integer>> toRemove = new ArrayList<Map<String, Integer>>();
for (Map<String, Integer> map : list) {
if (toRemove.contains(map)) {
continue;
}
int id = map.get("id");
for (Map<String, Integer> otherMap : list) {
if (map.equals(otherMap)) {
continue;
}
int otherId = otherMap.get("id");
if (id == otherId) {
map.putAll(otherMap);
toRemove.add(otherMap);
}
}
}
list.removeAll(toRemove);
有没有更优雅的方式来实现这一点?
最佳答案
我会将结果组织在 map 的 Map
中
Map<Integer, Map<String,Integer>> mapOfMaps = new HashMap<Integer, Map<String,Integer>>();
for(Map<String,Integer> map : list){
Integer id = map.get("id");
Map<String,Integer> existingMap = mapOfMaps.get(id);
if(existingMap == null){
mapOfMaps.put(id, map);
}else{
existingMap.putAll(map);
}
}
正如我在上面评论的那样:如果您不需要需要对值求和(除了 id
映射不共享其他键,或者如果它们做值将被替换)
关于java - 如何通过某个键的值合并多个 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42292826/