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());
  }
相关推荐
吃不饱的得可可44 分钟前
【Linux】System V消息队列与责任链模式
linux·运维·责任链模式
五岳6 小时前
分库分表数据源ShardingSphereDataSource的Connection元数据误用问题分析
java·mysql·爬坑
带刺的坐椅7 小时前
迈向 MCP 集群化:Solon AI (支持 Java8+)在解决 MCP 服务可扩展性上的探索与实践
java·ai·llm·solon·mcp
G_H_S_3_7 小时前
【网络运维】Docker 存储:镜像层与数据卷的管理应用
linux·运维·网络·docker
鼠爷ねずみ7 小时前
SpringCloud前后端整体开发流程-以及技术总结文章实时更新中
java·数据库·后端·spring·spring cloud
代码or搬砖7 小时前
String字符串
android·java·开发语言
AM越.9 小时前
Java设计模式详解--装饰器设计模式(含uml图)
java·设计模式·uml
还鮟9 小时前
靶机远程控制实验命令与入门实践(Linux)
linux·网络·安全
5980354159 小时前
【java工具类】小数、整数转中文大写
android·java·开发语言