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());
  }
相关推荐
zzb15804 小时前
RAG from Scratch-优化-query
java·数据库·人工智能·后端·spring·mybatis
wuqingshun3141594 小时前
如何停止一个正在退出的线程
java·开发语言·jvm
朱包林4 小时前
Python基础
linux·开发语言·ide·python·visualstudio·github·visual studio
biubiubiu07065 小时前
Linux / Ubuntu systemd 服务使用说明
linux·运维·ubuntu
Barkamin5 小时前
队列的实现(Java)
java·开发语言
MaximusCoder6 小时前
等保测评命令——Anolis Linux
linux·运维·服务器·网络·经验分享·安全·php
骇客野人6 小时前
自己手搓磁盘清理工具(JAVA版)
java·开发语言
J2虾虾6 小时前
在SpringBoot中使用Druid
java·spring boot·后端·druid
清风徐来QCQ6 小时前
Java笔试总结一
java·开发语言
zhojiew6 小时前
为agent实现渐进式Skills能力的思考和实践
linux·python·算法