比如有5个list:
list A = {a,b,c}
list B = {d,e,f}
list c = {x,y,z,k,l}
list c = {1,2}
list c = {8,9,0,5}
要将几个list的内容进行组合,结果为 {adx18},{bey29},{efz0},{k5},{l}依次类推,实际情况可能会有更多的 list,list里元素也会更多
比如有5个list:
list A = {a,b,c}
list B = {d,e,f}
list c = {x,y,z,k,l}
list c = {1,2}
list c = {8,9,0,5}
要将几个list的内容进行组合,结果为 {adx18},{bey29},{efz0},{k5},{l}依次类推,实际情况可能会有更多的 list,list里元素也会更多
public static List<String> combination(List<List<String>> groups) {
if (invalid(groups) || invalid(groups.get(0))) {
return null;
}
List<String> combine = groups.get(0);
for (int i = 1; i < groups.size(); i++) {
combine = cartesianProduct(combine, groups.get(i));
if (combine == null) {
return null;
}
}
return combine;
}
/**
* 两个集合元素的组合
*
* @param c1 集合1
* @param c2 集合2
* @return 组合结果
*/
public static List<String> cartesianProduct(List<String> c1, List<String> c2) {
if (invalid(c1) || invalid(c2)) {
return null;
}
List<String> combine = new ArrayList<>();
for (int index = 0,size = c1.size(); index < size; index++) {
String s = "";
if (index<=c2.size()-1){
s = c2.get(index);
}
combine.add(String.format("%s%s", s, c1.get(index)));
}
return combine;
}
/**
* 验证集合是否无效
*
* @param c 集合
* @return true 无效
*/
private static boolean invalid(List<?> c) {
return c == null || c.isEmpty();
}
public static void main(String[] args) {
List<String> c1 = new ArrayList<>(Arrays.asList("a", "b", "c", "d"));
List<String> c2 = new ArrayList<>(Arrays.asList("1", "2", "3", "4"));
List<String> c3 = new ArrayList<>(Arrays.asList("I", "II", "III"));
List<List<String>> collections = new ArrayList<>();
collections.add(c1);
collections.add(c2);
collections.add(c3);
List<String> combine = combination(collections);
System.out.println(combine);
System.out.println("actual count: " + (combine == null ? 0 : combine.size()));
}
输出结果:[I1a, II2b, III3c, 4d]
actual count: 4
15 回答8.4k 阅读
8 回答6.2k 阅读
1 回答3k 阅读✓ 已解决
1 回答4k 阅读✓ 已解决
3 回答6k 阅读
3 回答2.2k 阅读✓ 已解决
2 回答3.1k 阅读