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());
  }
相关推荐
小短腿乄15 分钟前
java实现pdf加水印+签名
java·开发语言·pdf
常乐か26 分钟前
在 Ubuntu 24.04 中编译 Qt 5.15.2 项目完全指南
linux·qt·ubuntu
云烟成雨TD35 分钟前
Micrometer 系列【29】源码分析:MeterRegistry 实例化流程
java·云原生·micrometer
聆风吟º38 分钟前
【金仓数据库征文】Java 应用接入金仓数据库:从驱动、连接池到存储过程调试的踩坑实录
java·开发语言·数据库
垂直昵称1 小时前
多线程实现网页接口并发压力测试
linux·服务器·windows
似璟如你2 小时前
Java 开发者的 Go 语法基础:从 0 开始快速上手 Go
java·开发语言·后端·golang·go·编程语言
zzz_23682 小时前
TencentDB-Agent-Memory 深度解析:让多个 Agent 共享项目经验的记忆中枢
java·开发语言·jvm·人工智能·agent·memory·tencent db
jufeng13072 小时前
【系列:MiniKV 原理剖析 · 第 2 篇】
linux·c++·软件工程
王琦03182 小时前
Linux的管理程序
linux·运维·服务器
vx-程序开发3 小时前
django医院预约挂号系统---附源码23353
java·javascript·spring boot·python·eclipse·django·php