将列表列表转换为列表列表 [英] Convert a map of lists into a list of maps

查看:75
本文介绍了将列表列表转换为列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表列表,例如:

I have a map of lists like:

Map("a" -> [1,2,3], "b" -> [4,5,6], "c" -> [7])

我需要生产:

[
Map("a" -> 1, "b" -> 4, "c" -> 7),
Map("a" -> 1, "b" -> 5, "c" -> 7),
Map("a" -> 1, "b" -> 6, "c" -> 7),
Map("a" -> 2, "b" -> 4, "c" -> 7),
Map("a" -> 2, "b" -> 5, "c" -> 7),
Map("a" -> 2, "b" -> 6, "c" -> 7),
Map("a" -> 3, "b" -> 4, "c" -> 7),
Map("a" -> 3, "b" -> 5, "c" -> 7),
Map("a" -> 3, "b" -> 6, "c" -> 7),
]

我正在使用一个名为Vavr的Java库作为我的容器类型,但是我不介意以任何语言完成该实现.

I am using a Java library called Vavr for my container types but I don't mind seeing the implementation done in any language.

推荐答案

您可以首先遍历地图条目,并将列表元素表示为 Map< String,Integer> 并获取地图列表,然后

You can first iterate through map entries and represent list elements as Map<String,Integer> and get a stream of lists of maps, and then reduce this stream to a single list.

在线试试吧!

Map<String, List<Integer>> mapOfLists = new LinkedHashMap<>();
mapOfLists.put("a", List.of(1, 2, 3));
mapOfLists.put("b", List.of(4, 5, 6));
mapOfLists.put("c", List.of(7));

List<Map<String, Integer>> listOfMaps = mapOfLists.entrySet().stream()
        // Stream<List<Map<String,Integer>>>
        .map(entry -> entry.getValue().stream()
                // represent list elements as Map<String,Integer>
                .map(element -> Map.of(entry.getKey(), element))
                // collect a list of maps
                .collect(Collectors.toList()))
        // intermediate output
        //[{a=1}, {a=2}, {a=3}]
        //[{b=4}, {b=5}, {b=6}]
        //[{c=7}]
        .peek(System.out::println)
        // reduce a stream of lists to a single list
        // by sequentially multiplying the list pairs
        .reduce((list1, list2) -> list1.stream()
                // combinations of elements,
                // i.e. maps, from two lists
                .flatMap(map1 -> list2.stream()
                        .map(map2 -> {
                            // join entries of two maps
                            Map<String, Integer> map =
                                    new LinkedHashMap<>();
                            map.putAll(map1);
                            map.putAll(map2);
                            return map;
                        }))
                // collect into a single list
                .collect(Collectors.toList()))
        .orElse(null);

// output
listOfMaps.forEach(System.out::println);
//{a=1, b=4, c=7}
//{a=1, b=5, c=7}
//{a=1, b=6, c=7}
//{a=2, b=4, c=7}
//{a=2, b=5, c=7}
//{a=2, b=6, c=7}
//{a=3, b=4, c=7}
//{a=3, b=5, c=7}
//{a=3, b=6, c=7}


另请参阅:
通过替换隐藏的#数字符号来生成所有可能的字符串组合
如何从两个数组中获取所有可能的组合?


See also:
• Generate all possible string combinations by replacing the hidden # number sign
• How to get all possible combinations from two arrays?

这篇关于将列表列表转换为列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆