【发布时间】:2016-04-08 12:34:09
【问题描述】:
我有一个嵌套映射列表(List<Map<String, Map<String, Long>>>),目标是将列表减少为单个映射,合并如下:如果map1包含x->{y->10, z->20}和map2包含x->{y->20, z->20},那么这两个应该合并到x->{y->30, z->40}。
我尝试按照以下方式进行操作,效果很好。
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;
public class Test {
public static void main(String args[]) throws IOException {
Map<String, Map<String, Long>> data1 = new HashMap<>();
Map<String, Long> innerData1 = new HashMap<>();
innerData1.put("a", 10L);
innerData1.put("b", 20L);
data1.put("x", innerData1);
Map<String, Long> innerData2 = new HashMap<>();
innerData2.put("b", 20L);
innerData2.put("a", 10L);
data1.put("x", innerData1);
Map<String, Map<String, Long>> data2 = new HashMap<>();
data2.put("x", innerData2);
List<Map<String, Map<String, Long>>> mapLists = new ArrayList<>();
mapLists.add(data1);
mapLists.add(data2);
Map<String, Map<String, Long>> result = mapLists.stream().flatMap(map -> map.entrySet().stream()).
collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, new BinaryOperator<Map<String, Long>>() {
@Override
public Map<String, Long> apply(Map<String, Long> t,
Map<String, Long> u) {
Map<String, Long> result = t;
for(Entry<String, Long> entry: u.entrySet()) {
Long val = t.getOrDefault(entry.getKey(), 0L);
result.put(entry.getKey(), val + entry.getValue());
}
return result;
}
}));
}
}
还有其他更好更有效的方法来解决这个问题吗?
如果嵌套层数大于2,怎么做更干净?假设 List 类似于 List<Map<String, Map<String, Map<String, Long>>>>,我们必须将其缩减为单个 Map<String, Map<String, Map<String, Long>>>,并假设与上述类似的合并功能。
【问题讨论】:
标签: java lambda java-8 java-stream