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());
  }
相关推荐
小七mod3 分钟前
【Spring】Java SPI机制及Spring Boot使用实例
java·spring boot·spring·spi·双亲委派
深度学习040714 分钟前
【Linux服务器】-安装ftp与sftp服务
linux·运维·服务器
亿.628 分钟前
【Java安全】RMI基础
java·安全·ctf·rmi
ruan11451443 分钟前
Java Lambda 类型推断详解:filter() 方法与 Predicate<? super T>
java·开发语言·spring·stream
朱杰jjj1 小时前
解决jenkins的Exec command命令nohup java -jar不启动问题
java·jenkins·jar
上上迁1 小时前
分布式接口幂等性的演进和最佳实践,含springBoot 实现(Java版本)
java·spring boot·分布式
匚WYHaovous1 小时前
Java断言的深度解析与实战指南
java
WanderInk1 小时前
揭秘Java协变返回类型:让你的API少一点强转,多一点优雅
java·后端
paopaokaka_luck1 小时前
基于SpringBoot+Vue的非遗文化传承管理系统(websocket即时通讯、协同过滤算法、支付宝沙盒支付、可分享链接、功能量非常大)
java·数据库·vue.js·spring boot·后端·spring·小程序
iteye_99391 小时前
让 3 个线程串行的几种方式
java·linux