我正在尝试将大小为 3n
的 arrayList
拆分为 3 部分(每个部分的大小为 n),
但我只得到第一个一。我该如何解决这个问题?
[1,2,3,4,5,6,7,8,9] ==> [1,2,3][4,5,6][7,8,9]
感谢任何帮助。
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);
}
最佳答案
您可以使用subList(int fromIndex,int toIndex)像这样 -
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;
}
关于java - arraylist 部分到 3 个字符串部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30798006/