如有数组[["白色","黑色"],["64GB","128GB"],["中国移动","中国联通"]]要拼接返回一个数组如["白色/64GB/中国移动","黑色/64GB/中国移动","白色/128GB/中国移动","黑色/128GB/中国移动","白色/64GB/中国联通","黑色/64GB/中国联通","白色/128GB/中国联通","黑色/128GB/中国联通"]
有大神在吗?
4 回答
侃侃尔雅
TA贡献1801条经验 获得超16个赞
public class test {
public static List> source;
public static void main(String[] args) {
source = new ArrayList<>();
List<String> a = new ArrayList<String>();
a.add("黑色");
a.add("白色");
List<String> b = new ArrayList<String>();
b.add("64G");
b.add("128G");
List<String> c = new ArrayList<String>();
c.add("中国联通");
c.add("中国移动");
source.add(a);
source.add(b);
source.add(c);
ArrayList<String> result = new ArrayList<>();
recursion(result, source.get(0), 0, "");
System.out.println(result);
}
public static void recursion(List<String> result, List<String> para, int num, String choose) {
for (int i = 0; i < para.size(); i++) {
if (source.size() == num + 1) {
result.add(choose + "/" + para.get(i));
} else {
recursion(result, source.get(num + 1), num + 1, choose + "/" + para.get(i));
}
}
}
}
倚天杖
TA贡献1828条经验 获得超3个赞
这是一个多个数组组合问题。
1.用for循环。用一个变量标记数组的个数,用length属性读取每个数组的长度,所以用for循环肯定是可以的。
2.用dfs(深度优先搜索)算法。
MMMHUHU
TA贡献1834条经验 获得超8个赞
List<String> colors = List.of("白色", "黑色");
List<String> sizes = List.of("64GB", "128GB");
List<String> ops = List.of("中国移动", "中国联通");
Stream.of(colors.toArray())
.map(color ->
Stream.of(sizes.toArray())
.map(size ->
Stream.of(ops.toArray())
.map(op -> String.format("%s/%s", size, op))
.collect(Collectors.toList()))
.flatMap(Collection::stream)
.map(concat -> String.format("%s/%s", color, concat))
.collect(Collectors.toList()))
.flatMap(Collection::stream)
.forEach(System.out::println);
输出:
白色/64GB/中国移动
白色/64GB/中国联通
白色/128GB/中国移动
白色/128GB/中国联通
黑色/64GB/中国移动
黑色/64GB/中国联通
黑色/128GB/中国移动
黑色/128GB/中国联通
添加回答
举报
0/150
提交
取消
