java中将List数据平均切分成N份

话不多说,直接上代码,直接用

java 复制代码
  public static <T> List<List<T>> averageList(List<T> source, int n) {
    List<List<T>> ret = new ArrayList<List<T>>();
    int number = source.size() / n;
    int remainder = source.size() % n; // 取余
    int offset = 0;//偏移量
    for (int i = 0; i < n; i++) {
      System.out.println("i:"+i);
      List<T> value = null;
      if (remainder > 0) {
        value = source.subList(i * number + offset, (i + 1) * number + offset + 1);
        remainder--;
        offset++;
      } else {
        value = source.subList(i * number + offset, (i + 1) * number + offset);
      }
      ret.add(value);
    }
    return ret;
  }

如果想要再去除这里面存在的多余的空list,就加这行代码:

java 复制代码
  public static <T> List<List<T>> removeEmptyList(List<T> source, int n){
    List<List<T>> lists = averageList(source, n);
    return lists.stream().filter(i -> i.size() != 0).collect(Collectors.toList());
  }
相关推荐
程序猿DD8 分钟前
Java 25 中的 6 个新特性解读
java·后端
稻草猫.12 分钟前
文件 IO
java·笔记·后端·java-ee·idea
laopeng30113 分钟前
基于Spring AI Deep Researcher Agent
java·人工智能·spring
子豪-中国机器人26 分钟前
《C++ STL 基础入门》教案
java·开发语言
java_t_t31 分钟前
集合工具类
java·集合
消失的旧时光-194336 分钟前
ScheduledExecutorService
android·java·开发语言
勇闯逆流河37 分钟前
【C++】用红黑树封装map与set
java·开发语言·数据结构·c++
刘某的Cloud37 分钟前
磁盘-IO
linux·运维·系统·磁盘io
SpiderPex1 小时前
论MyBatis和JPA权威性
java·mybatis
我狸才不是赔钱货1 小时前
容器:软件世界的标准集装箱
linux·运维·c++·docker·容器