gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:47:35 25 4
gpt4 key购买 nike

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

示例:

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

最佳答案

以下应该可以解决问题,使用迭代方法并使用 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]]

关于java - 通过组合嵌套列表和复制单个值来扩展列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54577160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com