【问题标题】:List<Map<String, Object>> to List<Map<String, Object>> group by key with nullsList<Map<String, Object>> 到 List<Map<String, Object>> 按键分组
【发布时间】:2021-04-29 16:43:02
【问题描述】:

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

输入(列表>):

[
{"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}
]

预期输出(列表>):

[
{"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,因为数据总是不同的,但我总是知道键的名称是什么(例如:品牌在这种情况下)。 如您所见,我总是需要值而不是 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 格式的字符串即可。

【问题讨论】:

  • 数据总是不同是什么意思?如果数据总是不同,你想如何合并不同类型的对象?
  • 我的意思是键名可以不同,值的数量也可以不同。值本身将始终是数字或 NULL btw。

标签: java json java-stream


【解决方案1】:

您可以使用Collectors.toMapmergeFunction 来完成,根据brandMap&lt;String,Object&gt; 进行分组,然后在合并函数中编写逻辑以合并属性的值

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

【讨论】:

  • 非常感谢!奇迹般有效。那是我要找的! ;)
猜你喜欢
  • 2018-09-22
  • 1970-01-01
  • 2020-08-01
  • 1970-01-01
  • 2020-01-26
  • 1970-01-01
  • 2010-10-05
  • 2018-04-26
  • 1970-01-01
相关资源
最近更新 更多