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());
  }
相关推荐
老约家的可汗3 分钟前
Linux中基础IO
linux·服务器·算法
满怀冰雪15 分钟前
第29篇-状态压缩DP-当状态很多时如何降维优化
java·算法·动态规划
weixin_4467291617 分钟前
javaweb--文件上传
java
渡我白衣24 分钟前
打印宏与socket模块设计
java·linux·开发语言·c++·ide·人工智能·eclipse
AI创界者32 分钟前
打造内网安全防线:使用 Kali Linux 进行企业级漏洞风险自查与防御指南
linux·运维·安全
智码看视界35 分钟前
Day18 SpringBoot自动配置原理:从@SpringBootApplication开始
java·spring boot·后端·自动装配
weixin_4398575443 分钟前
在Ubuntu 26.04版本上借助本地AI助手在AMD显卡基础上安装并运行Qwen3.6-35B-A3B,作为本地编程AI
linux·人工智能·ubuntu
sanzk9 小时前
firefly开发板ubuntu安装ros2下的micro-ROS Agent
linux·运维·ubuntu
黒亱中旳9 小时前
Java AI 框架三国杀:Solon AI vs Spring AI vs LangChain4j 深度对比
java·人工智能·spring
网络工程小王9 小时前
[智能对话系统架构设计文档]
java·系统架构·langraph