通过合并嵌套列表和复制单个值来扩展列表

时间:2019-02-07 15:49:58

标签: java combinatorics

我有一个包含字符串和其他列表的列表。

示例:

List<Object> valuesList = new ArrayList<Object>();
valuesList.add("v0");
valuesList.add(Arrays.asList("v11", "v12"));
valuesList.add(Arrays.asList("v21", "v22"));
valuesList.add("v3");

我必须创建一个新的字符串列表,其中包含嵌套列表的所有组合以及通过组合复制的简单字符串成员。抱歉,如果不清楚,请查看上面示例的清单列表,可能会更清楚:

list 1: v0 v11 v21 v3
list 2: v0 v12 v21 v3
list 3: v0 v11 v22 v3
list 4: v0 v12 v22 v3

1 个答案:

答案 0 :(得分:1)

以下应该使用重复的方法,并使用List<List<String>>而不是List<Object>来解决问题:

import java.util.*;

public class MyClass {
    public static void main(String args[]) {
        List<List<String>> baseLists = new ArrayList<>();
        baseLists.add(Arrays.asList("a01","a02"));
        baseLists.add(Arrays.asList("a11","a12"));
        baseLists.add(Arrays.asList("a21","a22","a23"));
        baseLists.add(Arrays.asList("a3"));
        System.out.println("Base lists: " + baseLists);
        List<List<String>> combinations = new ArrayList<>();
        // iterative solution
        baseLists.forEach(list -> {
                List<List<String>> newCombinations = new ArrayList();
                list.forEach(string -> {
                    List<List<String>> currentCombinations = new ArrayList();
                    // deep copy combinations
                    combinations.forEach(inlist -> currentCombinations.add(new ArrayList(inlist)));
                    if(currentCombinations.isEmpty()) {
                        currentCombinations.add(new ArrayList());
                    }
                    currentCombinations.forEach(inlist -> inlist.add(string));
                    newCombinations.addAll(currentCombinations);
                });
                combinations.clear();
                newCombinations.forEach(l -> combinations.add(l));
        });
        System.out.println("Combination lists: " + combinations);
    }
}

在这种情况下的输出是:

Base lists: [[a01, a02], [a11, a12], [a21, a22, a23], [a3]]
Combination lists: [[a01, a11, a21, a3], [a02, a11, a21, a3], [a01, a12, a21, a3], [a02, a12, a21, a3], [a01, a11, a22, a3], [a02, a11, a22, a3], [a01, a12, a22, a3], [a02, a12, a22, a3], [a01, a11, a23, a3], [a02, a11, a23, a3], [a01, a12, a23, a3], [a02, a12, a23, a3]]