java list 切分

package com.founder.tongyin.util;

import java.util.ArrayList;
import java.util.List;

/**
 * TODO
 *
 * @ClassName: ListUtil
 * @author: dh
 * @since: 2020/8/3 15:44
 */
public class ListUtil {

    public static <T> List<List<T>> splitList(List<T> list, int groupSize){
        int length = list.size();
        int num = ( length + groupSize - 1 )/groupSize ;
        List<List<T>> newList = new ArrayList<>(num);
        for (int i = 0; i < num; i++) {
            int fromIndex = i * groupSize;
            int toIndex = (i+1) * groupSize < length ? ( i+1 ) * groupSize : length ;
            newList.add(list.subList(fromIndex,toIndex)) ;
        }
        return  newList ;
    }


    public static <T> List<List<T>> splitListToNum(List<T> list, int num){
        int length = list.size();
        int groupSize = (int)Math.ceil(length*1.0 / num);
        List<List<T>> newList = new ArrayList<>(num);
        for (int i = 0; i < num; i++) {
            int fromIndex = i * groupSize;
            int toIndex = (i+1) * groupSize < length ? ( i+1 ) * groupSize : length ;
            newList.add(list.subList(fromIndex,toIndex)) ;
        }
        return  newList ;
    }

}

 

posted @ 2021-03-20 13:34  _Meditation  阅读(99)  评论(0编辑  收藏  举报