如有数组[["白色","黑色"],["64GB","128GB"],["中国移动","中国联通"]]
要拼接返回一个数组
如["白色/64GB/中国移动","黑色/64GB/中国移动","白色/128GB/中国移动","黑色/128GB/中国移动","白色/64GB/中国联通","黑色/64GB/中国联通","白色/128GB/中国联通","黑色/128GB/中国联通"]
有大神在吗?
如有数组[["白色","黑色"],["64GB","128GB"],["中国移动","中国联通"]]
要拼接返回一个数组
如["白色/64GB/中国移动","黑色/64GB/中国移动","白色/128GB/中国移动","黑色/128GB/中国移动","白色/64GB/中国联通","黑色/64GB/中国联通","白色/128GB/中国联通","黑色/128GB/中国联通"]
有大神在吗?
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));
}
}
}
}
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/中国联通
10 回答11.1k 阅读
15 回答8.4k 阅读
8 回答6.2k 阅读
1 回答4k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
2 回答3.1k 阅读
2 回答3.8k 阅读
可用不用递归,三层循环可以解决你的问题
最外层循环遍历颜色,第二层循环遍历容量第三层循环遍历运营商