List分组工具类

2023-01-31  本文已影响0人  King斌
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;

/**
 * List分组
 *
 */
@Slf4j
public class BatchListUtils {
    /**
     * 
    * 分组
    * @param list 列表
    * @param batchNumber 参数
    * @return 参数 参数
     */
    public static Map<Integer,List> splitGroup(List list, int batchNumber) {
        Map<Integer,List> groupMap=new HashMap<>();
        if (list == null || list.isEmpty() || batchNumber == 0) {
            log.error("分组时参数出现问题:list={},batchNumber={}",list,batchNumber); 
        } else {
            int total=list.size();
            int executeTimes = total%batchNumber == 0 ? (total/ batchNumber) : (total/ batchNumber + 1);
            int offset=0;
            int end=0;
            for(int executeIndex=1;executeIndex<=executeTimes;executeIndex++) {
                end=executeIndex*batchNumber;
                if(end>=total) {
                    end=total;
                }
                groupMap.put(executeIndex, list.subList(offset, end));
                offset=executeIndex*batchNumber;
            }
        }
        return groupMap;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读