列表<映射<字符串、对象>> 到 列表<映射<字符串、对象>>按键分组,带空值



我有一个用例,我需要从一个查询合并多行与相同的键。

输入(List<Map&lt字符串,Object>祝辞):

[
{"brand": "A", "sum of A": NULL, "sum of B": NULL, "sum of C": NULL, "sum of D": NULL},
{"brand": "B", "sum of A": 2700, "sum of B": 1500, "sum of C": NULL, "sum of D": NULL},
{"brand": "B", "sum of A": NULL, "sum of B": NULL, "sum of C": 1700, "sum of D": NULL},
{"brand": "C", "sum of A": 3000, "sum of B": NULL, "sum of C": NULL, "sum of D": NULL},
{"brand": "C", "sum of A": NULL, "sum of B": NULL, "sum of C": 6000, "sum of D": NULL},
{"brand": "D", "sum of A": 1000, "sum of B": 2000, "sum of C": 4000, "sum of D": 600}
]

期望输出(List<String,>>):

[
{"brand": "A", "sum of A": NULL, "sum of B": NULL, "sum of C": NULL, "sum of D": NULL},
{"brand": "B", "sum of A": 2700, "sum of B": 1500, "sum of C": 1700, "sum of D": NULL},
{"brand": "C", "sum of A": 3000, "sum of B": NULL, "sum of C": 6000, "sum of D": NULL},
{"brand": "D", "sum of A": 1000, "sum of B": 2000, "sum of C": 4000, "sum of D": 600}
]

我如何用Java流API实现这一点?我不能使用POJO,因为数据总是不同的,但我总是知道键的名称(在这种情况下,例如:brand)。正如您所看到的,我总是需要值而不是NULL,但是如果没有值,那么我们可以在输出中使用NULL。

并且在同一列中,同一键总是只有一个值。所以这是无效的输入:

[
{"brand": "B", "sum of A": 2700, "sum of B": 1500, "sum of C": NULL, "sum of D": NULL},
{"brand": "B", "sum of A": 1400, "sum of B": NULL, "sum of C": 1700, "sum of D": NULL}
]

我不需要输出的确切返回类型,只要它很容易转换为JSON格式的字符串。

您可以使用收集器来实现。与mergeFunction进行映射,根据brandMap<String,Object>进行分组,然后在merge函数中写入逻辑,对属性

的值进行merge。
Collection<Map<String,Object>> result =list.stream()
.collect(Collectors.toMap(
map -> map.get("brand"),
Function.identity(),
(existing, replacement) -> {
//logic to merge m1 & m2
replacement.forEach((key,val)-> {
existing.compute(key, (exKey, exVal) -> /*logic to sum*/)
});
return existing;
}))
.values();

最新更新