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());
  }
相关推荐
jarreyer1 分钟前
CentOS 7 无法使用 yum 安装软件
linux·运维·centos
没有bug.的程序员28 分钟前
Serverless 弹性扩容引发的全线熔断:Spring Boot 启动耗时从 1s 压缩至 0.3s 的物理级绞杀
java·spring boot·kubernetes·serverless·扩容·线上
bearpping31 分钟前
java进阶知识点
java·开发语言
独自破碎E33 分钟前
【面试真题拆解】你知道ThreadLocal是什么吗
java·jvm·面试
kkkkatoq34 分钟前
JAVA中的IO操作
java·开发语言
深蓝轨迹1 小时前
@Autowired与@Resource:Spring依赖注入注解核心差异剖析
java·python·spring·注解
不想看见4041 小时前
C++八股文【详细总结】
java·开发语言·c++
薛定谔的悦1 小时前
告别传统BMS!深度解读阳光电源 BM^2T 电池管理技术白皮书
linux·能源·储能·bms·ems
源远流长jerry1 小时前
DPDK MP (Multi-Process) 通道深度解析
linux·网络·架构·ip
huaweichenai1 小时前
java的数据类型介绍
java·开发语言