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 分钟前
rootfs 详解与裁剪优化记录
linux·c++·bsp
AI人工智能+电脑小能手40 分钟前
大白话说Java设计模式-08-建造者模式(业务实战篇)
java·设计模式·建造者模式·架构设计·对象构建
xbgRS1 小时前
java中的线程
java
二宝哥1 小时前
CentOS 7.9 离线安装 Nginx 并配置openssl1.1.1
linux·nginx·centos
程序员老陆2 小时前
说一说FFmpeg6在Linux平台的编译
linux·运维·服务器·ffmpeg
ChaHae-In2 小时前
MyBatis入门操作
java·mybatis
xcLeigh2 小时前
Go入门:短变量声明的陷阱与最佳实践
java·redis·golang·教程·变量
青山木2 小时前
Hot 100 --- 最小栈
java·数据结构·算法·leetcode
疯狂打码的少年2 小时前
【数据结构】栈的应用:表达式求值(后缀表达式)
java·数据结构·笔记·算法
szephyr2 小时前
腾讯云 ADP 智能体的 Skills 版本回滚总是回到旧配置,是缓存没清还是版本管理没开?
java·缓存·腾讯云