Java按照指定的长度把一个大集合拆分成多个小集合

Java按照指定的长度把一个大集合拆分成多个小集合

封装了一个方法,参数length是长度、list是待拆分的大集合(泛型可以传任意类型:Object、Map、String、Integer…),返回值是由拆分后的多个小集合组成的二维集合。

public static <T>List<List<T>> getSubList(int length,List<T> list){
    
    
    int size = list.size();
    int temp = size / length + 1;
    boolean result = size % length == 0;
    List<List<T>> subList = new ArrayList<>();
    for (int i = 0; i < temp; i++) {
    
    
        if (i == temp - 1) {
    
    
            if (result) {
    
    
                break;
            }
            subList.add(list.subList(length * i, size)) ;
        } else {
    
    
            subList.add(list.subList(length * i, length * (i + 1))) ;
        }
    }
    return subList;
}

猜你喜欢

转载自blog.csdn.net/weixin_50989469/article/details/121038374