【问题标题】:How to convert list of map to array of hash如何将地图列表转换为哈希数组
【发布时间】: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)转换为原始对象数组?
  • 是的。键的顺序相同。可以是嵌套地图。

标签: java arrays json list


【解决方案1】:

输入的 JSON 可以被读入一个映射列表 data 共享相同的键集,这个列表将被转换为一个对象数组的列表,这个列表的第一个元素是一个映射的键。

因此,首先应该创建字段名称数组,将其转换为Stream,然后与从data 列表中的每个映射的值中检索到的Stream&lt;Object[]&gt; 合并:

// using Jackson JSON to read the input
ObjectMapper mapper = new ObjectMapper();

String input = "[{\"id\":1, \"firstname\":\"First\", \"lastname\": \"Last\"}]";
List<Map<String, Object>> data = mapper.readValue(input, new TypeReference<>() {});

List<Object[]> output = Stream.concat(
        Stream.<Object[]>of(data.get(0).keySet().toArray()),
        data.stream().map(m -> m.values().toArray())
    )
    .collect(Collectors.toList());

System.out.printf("Result: {%n\t%s%n}%n", 
        output.stream().map(Arrays::toString).collect(Collectors.joining(", ")));

System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(output));

输出:

Result: {
    [id, firstname, lastname], [1, First, Last]
}
[ [ "id", "firstname", "lastname" ], [ 1, "First", "Last" ] ]

或者类似地,结果可能是基于地图的keySet()values 的原始集合列表,可以这样创建:

List<Collection> result = Stream.concat(
        Stream.of(data.get(0).keySet()),
        data.stream().map(Map::values)
).collect(Collectors.toList());

【讨论】:

    猜你喜欢
    • 2017-06-20
    • 2015-09-13
    • 1970-01-01
    • 2015-11-26
    • 2019-10-27
    • 2019-05-23
    • 2012-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多