I am trying to split my arrayList
which has the size 3n
to 3 part (with size n each),
but I am getting just the first one. How can I fix that?
[1,2,3,4,5,6,7,8,9] ==> [1,2,3][4,5,6][7,8,9]
I appreciate any help.
List<RootCreator> mainSublist = new ArrayList<RootCreator>();
int number = mainList.size()/3;
for(int i= 0 ; i < mainList.size()/3; i++){
int index = i*3 ;
List<RootCreator> sublist = mainList.subList(0, index);
mainSublist.addAll(sublist);
}
List<RootCreator> mainSublist = mainList.subList(0, mainList.size() / 3);
You can use subList(int fromIndex,int toIndex) like this -
static <T> List<List<T>> split(List<T> list, int n) {
List<List<T>> parts = new ArrayList<List<T>>();
int size = list.size();
for (int index = 0; index < size; index += n) {
parts.add(new ArrayList<T>(
list.subList(index, Math.min(size, index + n)))
);
}
return parts;
}
The main problem: you always call mainList.subList() with first argument 0.
List<RootCreator> mainSublist = new ArrayList<RootCreator>();
int number = mainList.size()/3;
int first = 0;
for(; first < mainList.size() - number; first+=number){
mainSublist.addAll(mainList.subList(first, first + number));
}
mainSublist.addAll(mainList.subList(first));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.