Lists.partition(List list, int size用法

 首先應該知道這個單詞怎麼讀

使用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、平均切分集合(借鑑文章地址 :https://www.jianshu.com/p/d0b6d686677d

/**
     * 將一個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);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章