如何在java中将一个数组拆分为多个数组?
我有一个数组如何在java中将一个数组拆分为多个数组?,java,Java,我有一个数组 [2,5,7,9,1,3,4,6,8] 我想要一个函数 List<List<Integer>> split(List<Integer> list, int n) 注意,该数字是平均采样的在库中有一个列表。分区方法 List<List<Integer>> split(List<Integer> list, int n) { return Lists.partition(list, n); } 列表拆分(列
[2,5,7,9,1,3,4,6,8]
我想要一个函数
List<List<Integer>> split(List<Integer> list, int n)
注意,该数字是平均采样的在库中有一个列表。分区
方法
List<List<Integer>> split(List<Integer> list, int n) {
return Lists.partition(list, n);
}
列表拆分(列表,int n){
返回列表。分区(列表,n);
}
给定多个箱子
List<List<Integer>> result = new ArrayList<>();
while(result.size()<bins){
result.add(new ArrayList<>());
}
int counter = 0;
for(Integer i: input){
result.get(counter++%bins).add(i);
}
List result=new ArrayList();
同时(result.size()尝试以下操作:
public static ArrayList<ArrayList<Integer>> split(ArrayList<Integer> list, int n){
ArrayList<ArrayList<Integer>> resultArrays = new ArrayList<>();
int pivot = 0;
// Creates n ArrayLists.
for(int i = 0 ; i < n ; i++){
resultArrays.add(new ArrayList<>());
}
// Add element from list to new ArrayLists.
while(pivot != list.size()){
int p = pivot%n;
resultArrays.get(p).add(list.get(pivot));
pivot++;
}
return resultArrays;
}
pivot
点列表
的元素。(从0到大小-1)
p
指向ArrayList的ArrayList
索引。(大到n,这里是4)
所以
列表拆分(列表,int n){
列表结果=新建ArrayList();
//将n个ArrayList添加到结果列表
IntStream.range(0,n).forEach(k->result.add(newarraylist());
//迭代输入列表并将一个元素添加到结果数组的一个内部列表中
迭代器i=list.Iterator();
while(i.hasNext()){
整数计数=0;
while(i.hasNext()&&count
您想要随机分隔吗?@Turamarth顺序不是same@Alonsample Average到目前为止您尝试了什么?我看不出有任何问题。实现split
非常简单。@Turamart在这种情况下的输入似乎指定了块的大小,在这种情况下,它将是块的数量。这这不是OP想要的。仔细看看预期的输出。顺序不同。
public static ArrayList<ArrayList<Integer>> split(ArrayList<Integer> list, int n){
ArrayList<ArrayList<Integer>> resultArrays = new ArrayList<>();
int pivot = 0;
// Creates n ArrayLists.
for(int i = 0 ; i < n ; i++){
resultArrays.add(new ArrayList<>());
}
// Add element from list to new ArrayLists.
while(pivot != list.size()){
int p = pivot%n;
resultArrays.get(p).add(list.get(pivot));
pivot++;
}
return resultArrays;
}
[2,1,8],
[5,3],
[7,4],
[9,6]
num / *(pivot) / ArrayList[p]
1: [2,5,7,9,1,3,4,6,8] -> ArrayList[0]
*
2: [2,5,7,9,1,3,4,6,8] -> ArrayList[1]
*
3: [2,5,7,9,1,3,4,6,8] -> ArrayList[2]
*
4: [2,5,7,9,1,3,4,6,8] -> ArrayList[3]
*
5: [2,5,7,9,1,3,4,6,8] -> ArrayList[0]
*
6: [2,5,7,9,1,3,4,6,8] -> ArrayList[1]
*
7: [2,5,7,9,1,3,4,6,8] -> ArrayList[2]
*
8: [2,5,7,9,1,3,4,6,8] -> ArrayList[3]
*
9: [2,5,7,9,1,3,4,6,8] -> ArrayList[0]
*
List<List<Integer>> split(List<Integer> list, int n){
List<List<Integer>> result = new ArrayList<>();
//add n ArrayLists to the result list
IntStream.range(0, n).forEach(k->result.add(new ArrayList<>()));
//iterate over the input list and add one element to one of the inner list of the result array
Iterator i = list.iterator();
while(i.hasNext()){
int count = 0;
while(i.hasNext() && count < n){
result.get(count).add((Integer) i.next());
count++;
}
}
return result;
}