栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

多个集合元素组合(java和js实现)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

多个集合元素组合(java和js实现)

曾经在项目开发时遇到一个让我头疼的需求:进行试验设计时,有多个试验因子的多个因子水平需要进行全因子组合,因子数及其对应的因子水平数均不确定,由前端用户界面传入后台。
如:某次试验共有3个因子,因子一有2个因子水平,分别取值为[1,2];因子二有3个因子水平,分别取值为[3,4,5];因子三有2个因子水平,分别取值为[6,7];则此次试验一共有232=12种组合。组合结果列举:[[1, 3, 6], [1, 4, 6], [1, 5, 6], [2, 3, 6], [2, 4, 6], [2, 5, 6], [1, 3, 7], [1, 4, 7], [1, 5, 7], [2, 3, 7], [2, 4, 7], [2, 5, 7]]。假如因子只有两个,两层for循环遍历即可实现,如果有三个,则需要三层for循环嵌套,依此类推,因子组合代码几乎无法实现。
粗暴地遍历数组不可行,于是,我转换了思路,分两步实现,第一步:先组合第一个和第二个;第二步:将此前组合好的数据与后续依次组合。

上代码( 将需要组装的集合数据放入集合作为参数传入composeDatas方法即可,方法支持泛型,支持传入任何一种数据格式):

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ListUtil {
    public static  List> composeDatas(List> datas) {
        if(datas == null){
            return new ArrayList<>();
        }
        if(datas.size() < 2){//少于两个元素,没有意义,原样返回
            return datas;
        }
        List> result = new ArrayList<>();
        for(int i=0;i List> composeTwoLists(List list1, List list2){
        List> list = new ArrayList<>();
        for(int i=0;i list3 = new ArrayList<>();
                list3.add(list1.get(i));
                list3.add(list2.get(j));
                list.add(list3);
            }
        }
        return list;
    }

    
    public static  List> composeTwoLists2(List> list, List list1) {
        int totalSize = list.size() * list1.size();
        List> resultList = new ArrayList<>();
        for(int i=0;i list_j = list.get(j);
                list_j.add(list1.get(i));
            }

            //经过上一步的组合,list中每个元素均增加了一个元素。
            // 下一步:将list中的元素拷贝一份加入到最终结果集合中
            for(int k=0;k listCopy = null;
                try{
                    listCopy = deepCopy(list.get(k));//深拷贝
                }catch (Exception e){
                    e.printStackTrace();
                }
                if(listCopy != null){
                    resultList.add(listCopy);
                }
            }
            if(resultList.size() != totalSize){//完成最终结果集合构造前,遍历结束时需清除list中的末尾元素
                //将集合中所有元素的最后一个元素去掉(为下一轮组合作准备)
                // 与list1组合时,list中每个集合均在末尾增加了一个元素,一轮结束后,先清除那个元素,再进行下一轮
                // (下一轮遍历时,list中每个元素与list1中下一个元素组合)
                for (int l = 0; l < list.size(); l++) {
                    list.get(l).remove(list.get(l).size() - 1);
                }
            }
        }
        return resultList;
    }

    
    public static  List deepCopy(List src) throws IOException, ClassNotFoundException {
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(byteOut);
        out.writeObject(src);

        ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
        ObjectInputStream in = new ObjectInputStream(byteIn);
        @SuppressWarnings("unchecked")
        List dest = (List) in.readObject();
        return dest;
    }
}

测试代码(构造简单的测试数据,传入参数为[[1,2],[3,4,5],[6,7]]):

public static void main(String[] args) {
        List> list = new ArrayList<>();
        List list1 = Arrays.asList(1,2);
        List list2 = Arrays.asList(3,4,5);
        List list3 = Arrays.asList(6,7);
        list.add(list1);
        list.add(list2);
        list.add(list3);
        list = ListUtil.composeDatas(list);
        System.out.println("组合后的集合:");
        System.out.println(list);
        System.out.println("组合后的集合元素个数:");
        System.out.println(list.size());
    }

结果打印(整理后):

组合后的集合:
[
  [1, 3, 6], [1, 4, 6], [1, 5, 6], 
  [2, 3, 6], [2, 4, 6], [2, 5, 6], 
  [1, 3, 7], [1, 4, 7], [1, 5, 7], 
  [2, 3, 7], [2, 4, 7], [2, 5, 7]
]
组合后的集合元素个数:
12

传入复杂参数,如每个因子有其对应的因子ID及具体数值:

public static void main(String[] args) {
        List>> list = new ArrayList<>();

        List> list1 = new ArrayList<>();
        Map map1 = new HashMap<>();
        map1.put("factor_id", 1);
        map1.put("value", 11);
        list1.add(map1);
        Map map2 = new HashMap<>();
        map2.put("factor_id", 2);
        map2.put("value", 22);
        list1.add(map2);

        List> list2 = new ArrayList<>();
        Map map3 = new HashMap<>();
        map3.put("factor_id", 3);
        map3.put("value", 33);
        list2.add(map3);
        Map map4 = new HashMap<>();
        map4.put("factor_id", 4);
        map4.put("value", 44);
        list2.add(map4);
        Map map5 = new HashMap<>();
        map5.put("factor_id", 5);
        map5.put("value", 55);
        list2.add(map5);

        List> list3 = new ArrayList<>();
        Map map6 = new HashMap<>();
        map6.put("factor_id", 6);
        map6.put("value", 66);
        list3.add(map6);
        Map map7 = new HashMap<>();
        map7.put("factor_id", 7);
        map7.put("value", 77);
        list3.add(map7);

        list.add(list1);
        list.add(list2);
        list.add(list3);

        list = ListUtil.composeDatas(list);
        System.out.println("组合后的集合:");
        System.out.println(list);
        System.out.println("组合后的集合元素个数:");
        System.out.println(list.size());
    }

结果打印(整理后):

组合后的集合:
[
  [{factor_id=1, value=11}, {factor_id=3, value=33}, {factor_id=6, value=66}], 
  [{factor_id=1, value=11}, {factor_id=4, value=44}, {factor_id=6, value=66}], 
  [{factor_id=1, value=11}, {factor_id=5, value=55}, {factor_id=6, value=66}], 
  [{factor_id=2, value=22}, {factor_id=3, value=33}, {factor_id=6, value=66}], 
  [{factor_id=2, value=22}, {factor_id=4, value=44}, {factor_id=6, value=66}], 
  [{factor_id=2, value=22}, {factor_id=5, value=55}, {factor_id=6, value=66}], 
  [{factor_id=1, value=11}, {factor_id=3, value=33}, {factor_id=7, value=77}], 
  [{factor_id=1, value=11}, {factor_id=4, value=44}, {factor_id=7, value=77}], 
  [{factor_id=1, value=11}, {factor_id=5, value=55}, {factor_id=7, value=77}], 
  [{factor_id=2, value=22}, {factor_id=3, value=33}, {factor_id=7, value=77}], 
  [{factor_id=2, value=22}, {factor_id=4, value=44}, {factor_id=7, value=77}], 
  [{factor_id=2, value=22}, {factor_id=5, value=55}, {factor_id=7, value=77}]
]
组合后的集合元素个数:
12

本人是java开发,以java的思维方式结合js的语法,写了一套js实现,如下:

		let arr = [[1,2,3],[4,5],[6,7]];
		console.log("输入:");
		console.log(arr);
		
		let arr0 = [];
		
		function composeDatas(array){
			for(let i=0;i 

完美,不过公司资深前端拿到代码一看不禁皱眉了,这都什么跟什么啊,这么多for循环,也太复杂了吧,利用数组的reduce方法,很简单的递归就可搞定,上代码:

		let arr = [[1,2,3],[4,5],[6,7]];
		
		console.log("输入:");
		console.log(arr);
		
		list = arr.reduce(function(prev,cur,index,array){
			let arr1 = [];
			prev.forEach(item=>{
				let arr2 = [];
				if(!Array.isArray(item)){
					arr2.push(item);
				}else{
					arr2 = item;
				}
				cur.forEach(val=>{
					arr2.push(val);
					let arr3 = [];
					arr3 = [...arr2];
					arr1.push(arr3);
					arr2.splice(arr2.length - 1, 1);
				});
			});
			return arr1;
		});
		console.log("输出:");
		console.log(list);

貌似确实简单多了!!!

希望java也能利用递归更轻松地实现这个功能,碾压arr.reduce,有解决方案的大神留言,帮帮忙!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/782811.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号