执行完全外连接的一种方法是首先构造将月份值链接到映射本身并获取列表中的值的 a:Map<String, Map<String, Object>>
//first concatenate the two lists
Map<String, Map<String, Object>> result = Stream.concat(list1.stream(),
list2.stream())
//then collect in a map where the key is the value of the month
.collect(toMap(m -> (String) m.get("Month"),
//the value is the map itself
m -> m,
//merging maps (i.e. adding the "Sales" and "NoOfTranx" infos)
(m1, m2) -> {m1.putAll(m2); return m1; }));
//finally put that in a list
List<Map<String, Object>> merge = new ArrayList<>(result.values());
笔记:
- 修改原始地图 - 如果这是不希望的,您可以在合并部分中创建一个。
new HashMap<>()
- 对于左/右外连接,您只能流式传输一个列表,并在流中添加相关条目
- 对于内部连接,您可以从其中一个列表开始,过滤另一个列表中存在的元素,然后继续如上所述
下面打印的完整示例:
list1 = [{Month=August-13, Sales=282200}, {Month=July-13, Sales=310400}]
list2 = [{Month=August-13, NoOfTranx=6700}, {Month=July-13, NoOfTranx=14400}]
merge = [{Month=August-13, Sales=282200, NoOfTranx=6700}, {Month=July-13, Sales=310400, NoOfTranx=14400}]
法典:
public static void main(String[] args) {
List<Map<String, Object>> list1 = new ArrayList<>();
list1.add(map("Month", "August-13", "Sales", 282200));
list1.add(map("Month", "July-13", "Sales", 310400));
System.out.println("list1 = " + list1);
List<Map<String, Object>> list2 = new ArrayList<>();
list2.add(map("Month", "August-13", "NoOfTranx", 6700));
list2.add(map("Month", "July-13", "NoOfTranx", 14400));
System.out.println("list2 = " + list2);
Map<String, Map<String, Object>> result = Stream.concat(list1.stream(),
list2.stream())
.collect(toMap(m -> (String) m.get("Month"),
m -> m,
(m1, m2) -> {m1.putAll(m2); return m1; }));
List<Map<String, Object>> merge = new ArrayList<>(result.values());
System.out.println("merge = " + merge);
}
private static Map<String, Object> map(Object... kvs) {
Map<String, Object> map = new HashMap<>();
for (int i = 0; i < kvs.length; i += 2) {
map.put((String) kvs[i], kvs[i+1]);
}
return map;
}