public static <T> List<List<T>> partition(final List<T> list, final int size) {
if (list == null) {
throw new IllegalArgumentException("List must not be null");
}
if (size <= 0) {
throw new IllegalArgumentException("Size must be greater than 0");
}
List<List<T>> result = new ArrayList<>();
Iterator<T> it = list.iterator();
List<T> subList = null;
while(it.hasNext()) {
if(subList == null) {
subList = new ArrayList<>();
}
T t = it.next();
subList.add(t);
if(subList.size() == size) {
result.add(subList);
subList = null;
}
}
//补充最后一页
if(subList != null) {
result.add(subList);
}
return result;
}
上面的算法,
其实用这个方法可以代替:
org.apache.commons.collections4.ListUtils.partition(final List<T> list, final int size);