1.在控制台输出笛卡尔积:
public static void decare(int index,List<List<String>> all,List<String> temp) {
List<String> list = all.get(index);
int allSize = all.size();
int removeCount = allSize - index ;
for (int i=0;i<list.size();i++) {
String value = list.get(i);
if(i>0) {
for(int j=0;j<removeCount;j++) {
temp.remove(temp.size()-1);
}
}
temp.add(value);
if(index==allSize-1) {
System.out.println(temp);
}
if(index<allSize-1) {
decare(index+1,all,temp);
}
}
}
调用方法:
decare(0,all,new ArrayList<>());
2.若想调用方法返回给调用方,需要修改返回值类型
//定义一个接受返回值的List
List<String> dekaerList = new ArrayList<>();
//调用方法
List decare = decare(0, lists, new ArrayList<>(), dekaerList);
public static List<String> decare(int index, List<List<String>> all, List<String> temp,List<String> dekaerLists) {
List<String> list = all.get(index);
int allSize = all.size();
int removeCount = allSize - index;
for (int i = 0; i < list.size(); i++) {
String value = list.get(i);
if (i > 0) {
for (int j = 0; j < removeCount; j++) {
temp.remove(temp.size() - 1);
}
}
temp.add(value);
if (index == allSize - 1) {
System.out.println(temp);
dekaerLists.addAll(temp);
}
if (index < allSize - 1) {
decare(index + 1, all, temp, count);
}
}
return dekaerLists;
}
3.map集合取笛卡尔积
将map转为list,利用上述方法进行转换
List lists = new ArrayList();
for (Map.Entry map2 : formaps.entrySet()) {
Object key = map2.getKey();
ArrayList value = (ArrayList) map2.getValue();
ArrayList<Object> list = new ArrayList<>();
for (Object o : value) {
list.add(key + "=" + o);
}
lists.add(list);
}
List<String> dekaerList = new ArrayList<>();
List decare = ReportUtil.decare(0, lists, new ArrayList<>(), dekaerList);
Map map = new HashMap<>();
int count=3; //一个大的list分割成多个小的list,每个小list里面有三个元素
List<List<String>> list = splitList(decare, count);
for (List<String> value : list) {
for (String o1 : value) {
String[] split1 = o1.split("=");
map.put(split1[0], split1[1]);
}
}
//len代表以指定元素个数分割开
public static List<List<T>> splitList(List<T> list, int len) {
if (list == null || list.size() == 0 || len < 1) {
return null;
}
List<List<T>> result = new ArrayList<List<T>>();
int size = list.size();
int count = (size + len - 1) / len;
for (int i = 0; i < count; i++) {
List<T> subList = list.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1)));
result.add(subList);
}
return result;
}