gpt4 book ai didi

java - 加入 Java 8 Collection API

转载 作者:搜寻专家 更新时间:2023-10-30 19:45:49 25 4
gpt4 key购买 nike

我有两个 List<Map<String, Object>>对象。

[{Month=August-2013, Sales=282200}, {Month=July-2013, Sales=310400}, 
{Month=June-2013, Sales=309600}, {Month=May-2013, Sales=318200},
{Month=September-2013, Sales=257800}]

[{Month=April-2013, NoOfTranx=8600}, {Month=August-2013, NoOfTranx=6700}, 
{Month=July-2013, NoOfTranx=14400}, {Month=June-2013, NoOfTranx=8500},
{Month=May-2013, NoOfTranx=14400}]

我要join(Merge)这两个列表在Month key 。如何使用新集合 FULL OUTER JOIN, RIGHT OUTER JOIN 在这些列表上执行多个连接操作(即 API 等) .

最佳答案

执行完全外部连接的一种方法是首先构造一个 Map<String, Map<String, Object>>将月份值链接到 map 本身并获取列表中的值:

//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());

注意事项:

  • 原始 map 已修改 - 如果您不希望这样做,您可以创建一个 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;
}

关于java - 加入 Java 8 Collection API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23563728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com