Most efficient way to convert/flatten entire map to list (keys & values together , not separately)

Something like this:

List<List<String>> listOflists =
    mapOfMaps.values()
             .stream()
             .map(m -> m.entrySet()
                        .stream()
                        .flatMap(e->Stream.of(e.getKey(),e.getValue()))
                        .collect(Collectors.toList()))
             .collect(Collectors.toList());

For each inner Map, you stream over the entrySet(), and create a stream of all the keys and values, which you collect into a List.

For example, if you initialize the Map with:

Map<Long,Map<String,String>> mapOfMaps = new HashMap<>();
mapOfMaps.put(1L,new HashMap());
mapOfMaps.put(2L,new HashMap());
mapOfMaps.get(1L).put("key1","value1");
mapOfMaps.get(1L).put("key2","value2");
mapOfMaps.get(2L).put("key3","value3");
mapOfMaps.get(2L).put("key4","value4");

You'll get the following List:

[[key1, value1, key2, value2], [key3, value3, key4, value4]]

Below is my version of solution. You can iterate over entry and add values to desired list accordingly.

        List<List<String>> list = map.
                values()
                .stream()
                .map(value -> {
                    List<String> list1 = new ArrayList<>();
                    for (Map.Entry<String, String> entry : value.entrySet()) {
                        list1.add(entry.getKey());
                        list1.add(entry.getValue());
                    }
                    return list1;
                })
                .collect(Collectors.toList());

Test Input:


        Map<Long, Map<String, String>> map = new HashMap<>();

        Map<String, String> submap1 = new HashMap<>();
        submap1.put("test", "test2");

        Map<String, String> submap2 = new HashMap<>();
        submap2.put("test6", "6");

        map.put(1l, submap1);
        map.put(2l, submap2);