Java 分批次遍历List集合

为什么80%的码农都做不了架构师?>>>   hot3.png

/*
 * @(#)BatchIterator.java 2014-9-13
 * 
 * Copy Right@ uuola
 */ 
package com.uuola.commons;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
 * 
 * 集合分批迭代
 * @author tangxiaodong
 * 创建日期: 2014-9-13
 * 
 */ public class BatchIterator implements Iterator> {     /**      * 当前的批次集合返回的元素个数      */     private int batchSize;     private List srcList;     private int index = 0;     private List result;     private int size = 0;     public BatchIterator(List srcList, int batchSize) {         if (0 >= batchSize) {             throw new RuntimeException(                     "Please do not be set less than or equal to '0' for GenericBatchIterator's batchSize !");         }         this.batchSize = batchSize;         this.srcList = srcList;         this.size = null == srcList ? 0 : srcList.size();         result = new ArrayList(batchSize);     }     @Override     public boolean hasNext() {         return index < size;     }     @Override     public List next() {         result.clear();         for (int i = 0; i < batchSize && index < size; i++) {             result.add(srcList.get(index++));         }         return result;     }     /**      * 暂不支持移除子集合方法      */     @Override     public void remove() {         throw new UnsupportedOperationException();     } }


使用方法:

.....

    private static void test4() {
        // TODO Auto-generated method stub
        List numbox = new ArrayList();
        Collections.addAll(numbox, 1, 2,3,4,5,6,7);
        Iterator> batchIter = new BatchIterator(numbox, 8);
        while (batchIter.hasNext()) {
            List nums = batchIter.next();
            System.out.println(nums);
        }
        System.out.println("test4 end --");
    }

......

转载于:https://my.oschina.net/hotkit/blog/323854

你可能感兴趣的:(Java 分批次遍历List集合)