D
D
DarkByte20152017-08-03 18:16:01
Java
DarkByte2015, 2017-08-03 18:16:01

Map of list to list of map?

There is a map from lists, it is necessary to make a list of maps out of it. Please tell me how to do it? So far, no ideas come to mind ... To make it clearer, I'll give an example (in json for clarity).
This is the original data:

{
  "field1": [ 1, 2, 3 ],
  "field2": [ true, false, true ]
}

And this should work:
[
  {
    "field1": 1,
    "field2": true
  },
  {
    "field1": 2,
    "field2": false
  },
  {
    "field1": 3,
    "field2": true
  }
]

PS It is possible (and even necessary) to use StreamAPI.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nick Smith, 2017-08-03
@DarkByte2015

The complexity is wild, but for ordinary cards it will do, the only thing is that sheets of the same size are needed.

public static void main(String[] args) {
        Map<String, List<Object>> map = new LinkedHashMap<>();
        map.put("field1", Arrays.asList(1, 2, 3));
        map.put("field2", Arrays.asList(true, false, true));
        map.put("field3", Arrays.asList("123", "456", "789"));
        map.put("field4", Arrays.asList(3, 2, 1));

        List<Map<String, Object>> result = IntStream.range(0, map.values().iterator().next().size())
                .mapToObj(index -> {
                    Map<String, Object> test = new LinkedHashMap<>();
                    map.forEach((s, objects) -> test.put(s, objects.get(index)));
                    return test;
                }).collect(Collectors.toList());

        System.out.println(result);
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question