public static List combination(List> groups) {
if (invalid(groups) || invalid(groups.get(0))) {
return null;
}
List 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 cartesianProduct(List c1, List c2) {
if (invalid(c1) || invalid(c2)) {
return null;
}
List 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 c1 = new ArrayList<>(Arrays.asList("a", "b", "c", "d"));
List c2 = new ArrayList<>(Arrays.asList("1", "2", "3", "4"));
List c3 = new ArrayList<>(Arrays.asList("I", "II", "III"));
List> collections = new ArrayList<>();
collections.add(c1);
collections.add(c2);
collections.add(c3);
List combine = combination(collections);
System.out.println(combine);
System.out.println("actual count: " + (combine == null ? 0 : combine.size()));
}
输出结果:[I1a, II2b, III3c, 4d]
actual count: 4