将List集合按长度切分

文章目录

  • 将List集合按长度切分
  • 1. 使用guava
  • 2. 使用commons-collection4
  • 3. 使用hutool

将List集合按长度切分

在日常工作中,经常会遇到需要将list集合进行拆分然后进行操作,比如像在tidb中一个事务默认最多5000条sql statement,或者mysql批量处理时候max_allowed_packet默认大小的限制,一般都需要去把对应数据的集合去拆分然后进行操作。

1. 使用guava

Lists.partition

List<Integer> list = Lists.newArrayList(1,2,3,4,5,6,7,8,9,10);
List<List<Integer>> listList = Lists.partition(list, 4);
listList.forEach(a -> System.out.println(a));

输出结果:

[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10]

pom文件:

<dependency>
    <groupId>com.google.guavagroupId>
    <artifactId>guavaartifactId>
    <version>20.0version>
dependency>

2. 使用commons-collection4

ListUtils.partition

List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
List<List<Integer>> listList = ListUtils.partition(list, 3);
listList.forEach(a -> System.out.println(a));

输出结果:

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
[10]

pom文件:

<dependency>
     <groupId>org.apache.commonsgroupId>
     <artifactId>commons-collections4artifactId>
     <version>4.1version>
 dependency>

3. 使用hutool

ListUtil.partition

List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
List<List<Integer>> listList = ListUtil.partition(list, 4);
listList.forEach(a -> System.out.println(a));

输出结果:

[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10]

pom文件:

<dependency>
    <groupId>cn.hutoolgroupId>
    <artifactId>hutool-allartifactId>
    <version>5.8.3version>
dependency>
  1. demo
package com.storm.jihe;

import cn.hutool.core.collection.ListUtil;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.ListUtils;

import java.util.Arrays;
import java.util.List;

/**
 * @author [email protected]
 * @date 2022/10/17 14:30
 */
public class SetSlice {
    public static void main(String[] args) {
        //guavaPartition();
        apachePartition();
        //hutoolPartition();
    }

    private static void hutoolPartition() {
        List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
        List<List<Integer>> listList = ListUtil.partition(list, 4);
        listList.forEach(a -> System.out.println(a));
    }

    private static void apachePartition() {
        List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
        List<List<Integer>> listList = ListUtils.partition(list, 3);
        listList.forEach(a -> System.out.println(a));
    }

    private static void guavaPartition() {
        List<Integer> list = Lists.newArrayList(1,2,3,4,5,6,7,8,9,10);
        List<List<Integer>> listList = Lists.partition(list, 4);
        listList.forEach(a -> System.out.println(a));
    }
}

你可能感兴趣的:(java,java,java集合切分)