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());
  }
相关推荐
东离与糖宝1 分钟前
OpenClaw 企业级实战:Java 微服务集成 AI 智能体,自动处理业务流
java·人工智能
不愿透露姓名的大鹏1 分钟前
VMware vcenter报错no healthy upstream
linux·运维·服务器·vmware
胡楚昊5 分钟前
Polar PWN (4)
linux·运维·算法
半瓶榴莲奶^_^5 分钟前
优先级队列(堆)
java·数据结构·算法
东离与糖宝6 分钟前
成本砍半!Java 生产环境 INT4/INT8 模型量化 + 提示词缓存落地
java·人工智能
Lyyaoo.6 分钟前
Spring中Bean的作用域与生命周期
java·后端·spring
遇见你...6 分钟前
B03 SpringMVC拦截器
java·开发语言
星晨雪海7 分钟前
缓存更新操作实例
java·spring·缓存
nangonghen9 分钟前
centos 7.9安装hiclaw
linux·运维·centos
東雪木10 分钟前
Java学习——接口 (interface) 与抽象类 (abstract) 的本质区别、选型标准
java·开发语言·jvm·学习·java面试