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 小时前
Mybatis实现批量插入
java·后端·mybatis
咖啡八杯4 小时前
GoF设计模式——中介者模式
java·后端·spring·设计模式
tntxia6 小时前
linux curl命令详解_curl详解
linux
青石路8 小时前
记一次多JDK版本问题的排查,一坑套一坑,差点没爬上来
java
扛枪的书生9 小时前
Linux 网络管理器用法速查
linux
像我这样帅的人丶你还11 小时前
Java 后端详解(五):Redis 缓存
java·后端·全栈
顺风尿一寸12 小时前
Java Socket 内核之旅:从 SocketChannel.read() 到 tcp_recvmsg 与 epoll 的完整调用链路
linux
plainGeekDev13 小时前
GreenDAO → Room
android·java·kotlin
XIAOHEZIcode18 小时前
Ubuntu 终端美化全栈指南:Bash 到 Kitty 踩坑实录
linux·ubuntu·命令行
亦暖筑序18 小时前
Java 8老系统AI Workflow实战:把一次性AI对话升级成可恢复工作流
java·后端