将List集合按长度切分

将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.guava</groupId>
    <artifactId>guava</artifactId>
    <version>20.0</version>
</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.commons</groupId>
     <artifactId>commons-collections4</artifactId>
     <version>4.1</version>
 </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.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.3</version>
</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 stormkai@126.com
 * @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));
    }
}
  • 6
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值