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());
  }
相关推荐
Jesse_EC12 分钟前
为什么我设置的 contentLength 到了消费端变成了 0?
java
vipxieliang12 分钟前
ValidX 的 Date 和 DateTime vs JPA 的 Temporal 对比
java·后端
杜touch14 分钟前
Spring框架的AnnotationConfigApplicationContext类启动的流程
java
小雪崩28 分钟前
嵌入式学习 day27:标准IO
linux·c语言·学习
Arnold.Shen40 分钟前
Dell Storage SC - 如何发送SupportAssist,并启用安全控制台
linux·安全
wunaiqiezixin1 小时前
MIT 6.S081 xv6 源码精读(Scheduling):sched、scheduler
linux·unix·os·xv6·mit6.s081
AI人工智能+电脑小能手1 小时前
大白话说Java设计模式-26-策略模式(业务实战篇)
java·spring·设计模式·策略模式·支付系统·算法切换
不是光头 强1 小时前
Java 后端 AI 技术选型与学习路线
java·人工智能·学习
书生执笔画浮沉2 小时前
记录一个由浮点运算引起的崩溃
linux
paopaokaka_luck2 小时前
基于springboot3+vue3的文山民族文化资源展示与推广平台(协同过滤算法、Echarts 图形化分析)
java·前端·spring boot·学习·echarts