List 分批处理

本文介绍了如何有效地对大型List进行分批处理,避免一次性加载大量数据导致的内存问题。通过使用迭代器或分页方法,可以实现高效地按批次操作列表元素,提高程序性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public interface BatchHandlerInterface<T> {
   /**
    * 分批回调方法
    * */
   public void handler(List<T> subList);
}

--------------------------------------------------------

public abstract class BatchHandlerList<T> implements BatchHandlerInterface<T> {
   
   private static final Logger LOGGER = Logger.getLogger(BatchHandlerList.class);
   //每次处理条数
   private Integer perNum;
   
   private List<T> aylist;

   public BatchHandlerList(Integer perNum, List<T> aylist) {
      super();
      this.perNum = perNum;
      this.aylist = aylist;
   }
   
   /**
    * 分批调用方法
    * */
   public void handlerList(){
      try{
         if(aylist!=null && aylist.size() > 0){
            int size = aylist.size();
            int startIndex = 0;
            int endIndex = 1;
            int num = 1;
            if (size > perNum) {
               num = size / perNum;
            }
            for (int i = 1; i <= num; i++) {
               try {
                  endIndex = (i) * perNum > size ? size : (i) * perNum;
                  List<T> subList = aylist.subList(startIndex, endIndex);
                  
                  startIndex = perNum * i;
                  if (subList!=null && subList.size() > 0) {
                     handler(subList);
                  }
                  
                  if (num == i && perNum * num < size) {
                     //最后一批处理
                     subList = aylist.subList(perNum * num, size);
                     if (subList.size() > 0) {
                        handler(subList);
                     }
                  }
               } catch (Exception e) {
                  LOGGER.error(" single batchHandlerList handler exception",e);
               }
            }
         }
      }catch(Throwable e){
         LOGGER.error("batchHandlerList handler exception",e);
         //错误回调方法可以重写
         errorHandler();
      }
   }
   
   public void errorHandler(){};
}

--------------------------------------

调用

BatchHandlerList<User> handlerList = new BatchHandlerList<AcpInfo>(200,acpInfoList) {
   @Override
   public void handler(List<User> subList) {
   
      for(Usera:subList){
         //逻辑处理
         logger.info("",subList);
      }
   }
};
handlerList.handlerList();
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值