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 天前
【Linux】人事档案——用户及组管理
linux·c++
青草地溪水旁1 天前
pthread_mutex_lock函数深度解析
linux·多线程·pthread
喵手1 天前
玩转Java网络编程:基于Socket的服务器和客户端开发!
java·服务器·网络
再见晴天*_*1 天前
SpringBoot 中单独一个类中运行main方法报错:找不到或无法加载主类
java·开发语言·intellij idea
太空的旅行者1 天前
告别双系统——WSL2+UBUNTU在WIN上畅游LINUX
linux·运维·ubuntu
人工智能训练师1 天前
Ubuntu22.04如何安装新版本的Node.js和npm
linux·运维·前端·人工智能·ubuntu·npm·node.js
灿烂阳光g1 天前
domain_auto_trans,source_domain,untrusted_app
android·linux
hdsoft_huge1 天前
Java & Spring Boot常见异常全解析:原因、危害、处理与防范
java·开发语言·spring boot
Ronin3051 天前
【Linux系统】日志与策略模式
linux·策略模式·日志
雨白1 天前
Java 多线程指南:从基础用法到线程安全
android·java