1. 首页
  2. 软件开发
  3. JAVA
  4. Lists.partition(List<T> list, int size用法

Lists.partition(List<T> list, int size用法

  • 发布于 2024-09-25
  • 1 次阅读

首先应该知道这个单词怎么读

使用partition()方法先引入jar包

      <dependency>
          <groupId>com.google.guava</groupId>
          <artifactId>guava</artifactId>
          <version>25.0-jre</version>
      </dependency>

1、将list(当然,也可以是其他集合)拆分成多份,常见的场景,比如批量执行sql、分批推送消息等。

(1)guava 实现(按照固定大小分片)

public static void main(String[] args) {
        List<Integer> numLists = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 1, 2, 3, 4, 4, 5, 6, 7, 78, 8, 9, 0,45,67,87);
        Collections.shuffle(numLists);
        List<List<Integer>> lists = Lists.partition(numLists, 6);
        Random random = new Random();
        lists.parallelStream().forEach(x -> {
            System.out.println(x.toString());
        });

(2)使用apache.commons.collection实现

import org.apache.commons.collections4.ListUtils;

public static void main(String[] args) {
        List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
        List<List<Integer>> lists = ListUtils.partition(intList, 3);
        lists.parallelStream().forEach(x-> System.out.println(x.toString()));

    }

2、平均切分集合(借鉴文章地址 :Java List操作1(分片 partition) - 简书)

/**
     * 将一个list均分成n个list,主要通过偏移量来实现的
     *
     * @param source
     * @return
     */
    public static <T> List<List<T>> averageAssignList(List<T> source, int n) {
        List<List<T>> result = new ArrayList<>();
        int remaider = source.size() % n;  //(先计算出余数)
        int number = source.size() / n;  //然后是商
        int offset = 0;//偏移量
        for (int i = 0; i < n; i++) {
            List<T> value = null;
            if (remaider > 0) {
                value = source.subList(i * number + offset, (i + 1) * number + offset + 1);
                remaider--;
                offset++;
            } else {
                value = source.subList(i * number + offset, (i + 1) * number + offset);
            }
            result.add(value);
        }
        return result;
    }


pubic static void main(String[] args){
        System.out.println("平均分list集合....");
        List<List<Integer>> assignList = averageAssignList(numLists, 5);
        assignList.parallelStream().forEach(x-> System.out.println(x.toString()));
} 

3、使用Java8 stream流 partition by , partitioningBy是一种特殊的分组,只会分成两组

System.out.println("使用Java8 stream流 partition by , partitioningBy是一种特殊的分组,只会分成两组");
        List<Integer> nums = Lists.newArrayList(1,1,8,2,3,4,5,6,7,9,10);
        Map<Boolean,List<Integer>> numMap= nums.stream().collect(Collectors.partitioningBy(num -> num > 5));
        System.out.println(numMap);

原文链接: https://onlyou.blog.csdn.net//article/details/103383135