如何将一个List进行拆分?
秉承封装的原则,单独建一个类,不放在工具类中了。实现java.lang.Iterable
接口,方便遍历。迭代器模式
public final class ListSplitter<E> implements Iterable<List<E>> {
private final List<E> list;
private final int batch;
private final List<List<E>> internalList = new ArrayList<>();
public ListSplitter(List<E> list, int batch) {
this.list = list;
this.batch = batch;
init();
}
private void init() {
List<E> tmpList = new ArrayList<>(this.list);
while (tmpList.size() > batch) {
internalList.add(tmpList.subList(0, batch));
tmpList = tmpList.subList(batch, tmpList.size());
}
if (tmpList.size() > 0) {
internalList.add(tmpList);
}
}
@Nonnull
@Override
public Iterator<List<E>> iterator() {
return this.internalList.iterator();
}
}
使用方法: