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());
  }
相关推荐
wljy19 分钟前
二、进制状态转换
linux·运维·服务器·c语言·c++
week@eight18 分钟前
Linux - Doris
linux·运维·数据库·mysql
平行云36 分钟前
实时云渲染预启动技术解析:UE数字孪生应用的延迟优化机制(二)
linux·unity·ue5·webgl·实时云渲染·云桌面·像素流
看到代码头都是大的1 小时前
CentOS环境下手动升级openssl、openssh
linux·运维·centos
浮生若城1 小时前
Linux——Ext系列文件系统
linux·运维·服务器
ZhengEnCi1 小时前
01-如何监听接口调用情况?
java·spring boot·后端
枳实-叶1 小时前
【Linux驱动开发】第16天:按键中断完整实战
linux·运维·驱动开发
JAVA面经实录9172 小时前
MyBatis学习体系
java·mybatis
java1234_小锋2 小时前
在 Spring AI 中如何实现函数调用(Function Calling)?请说明其基本原理和应用场景。
java·人工智能·spring
杨云龙UP3 小时前
Oracle Recycle Bin 回收站详解:DROP TABLE 后还能找回吗?
linux·运维·数据库·sql·mysql·oracle