【发布时间】:2021-02-11 12:36:42
【问题描述】:
我在我的应用程序中使用 Java。这是我的输入数据。
[{
"id": 1,
"firstname": "one",
"lastname": "1"
},
{
"id": 2,
"firstname": "two",
"lastname": "2"
},
{
"id": 3,
"firstname": "three",
"lastname": "3"
}
]
我想将上面的输入转换成下面的输出。如何以有效的方式实现以下输出?
{
["id", "firstname", "lastname"], [1, "one", "1"], [2, "two", "2"], [3, "three", "3"]
}
更新:
我已经尝试过以下方法。但结果如下
预期:
result => {[lastname, id, firstname]=[[1, 1, one], [2, 2, two], [3, 3, three]]}
实际:
结果 => {[姓氏, id, 名字], [1, 1, 一], [2, 2, 二], [3, 3, 三]}
代码:
Map<String, Object> one = Map.of("id", 1, "firstname", "one", "lastname", "1");
Map<String, Object> two = Map.of("id", 2, "firstname", "two", "lastname", "2");
Map<String, Object> three = Map.of("id", 3, "firstname", "three", "lastname", "3");
ArrayList<Map<String,Object>> list = new ArrayList<>();
list.add(one);
list.add(two);
list.add(three);
MultiValueMap<Object, Object> result = new LinkedMultiValueMap<>();
Set<String> strings = list.get(0).keySet();
ArrayList<Object> objects = new ArrayList<>();
for(Map<String,Object> map: list) {
objects.add(map.values());
}
result.put(strings, objects);
【问题讨论】:
-
您尝试了哪些方法,为什么没有成功?
-
另一件很高兴澄清的事情是您为什么要这样做?这听起来像是 XY 问题的一个案例。另外你的输入保证是什么?所有地图都有相同的键吗?
-
你能分享一下你解决这个问题的方法吗?
-
按键顺序是否一致?以及为什么需要将结构化对象(可以轻松映射到 POJO)转换为原始对象数组?
-
是的。键的顺序相同。可以是嵌套地图。