java 把一个大的数组按照元素数量拆分为多个小的数组
比如需要把数组
['a','b','c','d','f'],按照每3个为一组拆分为多个数组,如下
['a','b','c'],['a','b','d'],['a','b','f'],['a','c','d'],['a','c',''f],['a','d','f']
['b','c','d'], ['b','c','f'], ['b','d','f']
['c','d','f']
直接上代码
/*
* @Author gao
* @Description //把一个集合中的元素,按照指定传入的needNum的数量再拆分为多个小的集合
* ['a','b','c','d','f'],假设传入的needNum为3,则结果为
* ['a','b','c'],['a','b','d'],['a','b','f'],['a','c','d'],['a','c',''f],['a','d','f']
* ['b','c','d'], ['b','c','f'], ['b','d','f']
* ['c','d','f']
* @Param [addlist, begin, needNum, strings, result]
* @return void
**/
public static void sortCompareData(List<String> addlist, int begin, int needNum, String [] strings, List<List<String>> result){
for (int i = begin; i < strings.length; i++) {
addlist.add(strings[i]);
if (addlist.size() == needNum) {
//放到新集合中,防止下面的集合操作影响已存储数据
result.add(new ArrayList<>(addlist));
//移除掉当前位置的元素
addlist.remove(addlist.size()-1);
} else {
sortCompareData(addlist,i+1,needNum,strings,result);
//移除掉当前位置的元素
addlist.remove(addlist.size()-1);
}
}
}
其中
addlist为临时存储的集合,begin为从数组开始的位置,needNum为每个小数组拆分几个元素为一组,上面的例子中就为3,strings为源数组,result为拆分后存储的结果集