Java 地图中值的组合

Java Combinarion of Values in a Map

我有一张这种类型的地图:Map<String, List<String>>

地图包含此数据:

{
  A[a1, a2, a3]
  B[b1 ,b2]
  C[c1, c2]
}

我想获得这个:

a1,b1,c1
a1,b1,c2
a1,b2,c1
a2,b1,c1
a2,b1,c2
a2,b2,c1
a3,b1,c1
a3,b1,c2
a3,b2,c1

Java8 的最佳处理方法是什么?考虑到每个键可能包含很多值。

这是我写的代码:

Map<String, List<String>> mapPnMatricesImpact = stream(matrixValue.split("@"))
    .map(s -> s.split("\|"))
    .collect(Collectors.groupingBy(a -> a[0],
        Collectors.mapping(a -> a[1], Collectors.toList())));

mapPnMatricesImpact
    .forEach((key, value) -> {
        List<String> keys = new ArrayList<>();
        keys.add(key);
        Stream<List<String>> product = value.stream().flatMap(a ->
            keys.stream().flatMap(b -> Stream.of(Arrays.asList(a, b)))
        );
        product.forEach(p -> { logger.warn("zzz --> " + p); });
    });

你可以试试递归的方式。对于地图的每个键,您可以 select 一个元素并添加列表并继续为键的元素做。然后收集到列表中。

  List<List<String>> getAllCom(int index, List<List<String>> list, List<String> curr){
    if(index >= list.size()) return Arrays.asList(curr);
    List<List<String>> res = new ArrayList<>(); 
    for (String e : list.get(index)) {
      List<String> now = new ArrayList<>(curr);
       now.add(e);
       res.addAll(getAllCom(index + 1, list, now));
    }
    return res;
  }

演示:

Map<String, List<String>> data = new HashMap<>();
data.put("A", Arrays.asList("a1","a2","a3"));
data.put("B", Arrays.asList("b1","b2"));
data.put("C", Arrays.asList("c1","c2"));

List<List<String>> list = new ArrayList<>(data.values());
System.out.println(getAllCom(0, list, Collections.emptyList()));

输出:

[[a1, b1, c1], [a1, b1, c2], [a1, b2, c1], [a1, b2, c2], [a2, b1, c1], [a2, b1, c2], [a2, b2, c1], [a2, b2, c2], [a3, b1, c1], [a3, b1, c2], [a3, b2, c1], [a3, b2, c2]]