Java guava partition方法拆分集合&自定义集合拆分方法

日常开发中,经常遇到拆分集合处理的场景,现在记录2中拆分集合的方法。

1. 使用Guava包提供的集合操作工具栏 Lists.partition()方法拆分

首先,引入maven依赖

java 复制代码
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>21.0</version>
</dependency>

部分源码

java 复制代码
public static <T> List<List<T>> partition(List<T> list, int size) {
        Preconditions.checkNotNull(list);
        Preconditions.checkArgument(size > 0);
        return (List)(list instanceof RandomAccess ? new Lists.RandomAccessPartition(list, size) : new Lists.Partition(list, size));
    }

Lists.partition方法,根据传入的size,对list进行拆分

使用Demo

java 复制代码
 public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        list.add(6);
        list.add(7);
        List<List<Integer>> partition = Lists.partition(list, 3);
        partition.forEach(l -> System.out.println(JSONObject.toJSONString(l)));
}
2. 自定义集合拆分方法partition

使用List的 subList方法自定义集合拆分

java 复制代码
   /**
     * 分割集合
     *
     * @param list  原集合
     * @param count 分割后,每个集合大小
     * @return java.util.List<java.util.List<T>>
     **/
    public static <T> List<List<T>> partition(List<T> list, int count) {
        List<List<T>> result = new ArrayList<>();

        int total = list.size();
        int pageSize = total % count == 0 ? total / count : total / count + 1;
        for (int i = 0; i < pageSize; i++) {
            int start = i * count;
            int end = Math.min((start + count), total);
            List<T> ts = list.subList(start, end);
            result.add(ts);
        }
        return result;
    }

使用Demo

java 复制代码
public static void main(String[] args) {
        
        List<String> strList = new ArrayList<>();
        strList.add("一月");
        strList.add("二月");
        strList.add("三月");
        strList.add("四月");
        strList.add("五月");
        strList.add("六月");
        strList.add("七月");
        strList.add("八月");
        strList.add("九月");
        strList.add("十月");
        strList.add("十一月");
        List<List<String>> listList = partition(strList, 3);
        listList.forEach(l -> System.out.println(JSONObject.toJSONString(l)));
    }

输出结果

相关推荐
SimonKing3 小时前
OpenCode AI辅助编程,不一样的编程思路,不写一行代码
java·后端·程序员
FastBean3 小时前
Jackson View Extension Spring Boot Starter
java·后端
Seven975 小时前
剑指offer-79、最⻓不含重复字符的⼦字符串
java
皮皮林55114 小时前
Java性能调优黑科技!1行代码实现毫秒级耗时追踪,效率飙升300%!
java
冰_河14 小时前
QPS从300到3100:我靠一行代码让接口性能暴涨10倍,系统性能原地起飞!!
java·后端·性能优化
桦说编程17 小时前
从 ForkJoinPool 的 Compensate 看并发框架的线程补偿思想
java·后端·源码阅读
躺平大鹅19 小时前
Java面向对象入门(类与对象,新手秒懂)
java
初次攀爬者20 小时前
RocketMQ在Spring Boot上的基础使用
java·spring boot·rocketmq
花花无缺20 小时前
搞懂@Autowired 与@Resuorce
java·spring boot·后端