public class revertInterger {
public static void main(String[] args) {
Map<String, Object> map = new HashMap<>();
map.put("zhangsan","78");
map.put("lisi","79,80,81");
map.put("wangwu","12,7,6");
map.put("zhoaliu","3,0,68");
map.put("tianqi","66");
Map<String, Object> multiValueMap = new HashMap<>();
multiValueMap.put("lisi","79,80,81");
multiValueMap.put("wangwu","12,7,6");
multiValueMap.put("zhoaliu","3,0,68");
buildMultiMap(map,multiValueMap);
}
/**
* 一行拆分成多行
* @param map
* @param multiValueMap
* @return
*/
private static List<Map<String, Object>> buildMultiMap(Map<String, Object> map, Map<String, Object> multiValueMap) {
if(MapUtils.isEmpty(map)){
return Collections.emptyList();
}
if(MapUtils.isEmpty(multiValueMap)){
return Arrays.asList(map);
}
// 构建二维数组
int i = 0;
int crossJoinCount = 0;
String[][] crossJoin = new String[multiValueMap.entrySet().size()][];
// 构建列动态变化数组
int[] counter = new int[multiValueMap.entrySet().size()];
for (Map.Entry<String, Object> multiValueEntry : multiValueMap.entrySet()) {
String mapKey = multiValueEntry.getKey();
String mapValue = (String)multiValueEntry.getValue();
String[] splitArray = mapValue.split(",");
if(crossJoinCount==0){
crossJoinCount = splitArray.length;
} else {
crossJoinCount = crossJoinCount * splitArray.length;
}
crossJoin[i] = splitArray;
counter[i] = 0;
i++;
}
int counterIndex = crossJoin.length - 1;
List<Map<String, Object>> resultList = new ArrayList<>();
for(int j = 0; j< crossJoinCount;j++){
int k = 0;
Map<String, Object> itemMap = new HashMap<>();
for (Map.Entry<String, Object> entry : multiValueMap.entrySet()) {
itemMap.put(entry.getKey(),crossJoin[k][counter[k]]);
k++;
}
resultList.add(itemMap);
// 做列的动态变化
handle(counter,counterIndex,crossJoin);
}
return resultList;
}
/**
* 做每一列列号的遍历(从最后一列开始)
* @param counter
* @param counterIndex
* @param crossJoin
*/
private static void handle(int[] counter, int counterIndex, String[][] crossJoin) {
counter[counterIndex]++;
if (counter[counterIndex] >= crossJoin[counterIndex].length) {
counter[counterIndex] = 0;
counterIndex--;
if (counterIndex >= 0) {
handle(counter,counterIndex,crossJoin);
}
counterIndex = crossJoin.length - 1;
}
}
}
java实现笛卡尔乘积
最新推荐文章于 2024-07-10 21:37:49 发布