Try this:
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;
}
The result is the one you exactly you want.
[2,1,8],
[5,3],
[7,4],
[9,6]
pivot
points list
's element.(from 0 to the size-1)
p
points the ArrayList of ArrayList
's index.(As big as n, here 4)
So,
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]
*