java分割list变成list嵌套list的办法,分批处理

背景:java里面经常会遇到把一个list分批处理的需求,这个时候把一个list分割成list<List>嵌套是一个好办法。

解决办法三种:1.可以自己写一个普通的foreach循环多少次加到一个list里面,然后重新new一个list

2.使用guava的工具类

Lists.partition(要分割的list, 每个小list多少条数据)

3.使用apach的工具类commons-collections4

ListUtils.partition(要分割的list, 每个小list多少条数据)

代码demo

package formal.util.list;


import com.google.common.collect.Lists;
import org.apache.commons.collections4.ListUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : 
 * @date : 2019/11/2
 * @description:分批处理,分批插入 
 */
public class PartialList {

    public static void main(String[] args) {
        /*1.正常情况,使用guava工具类分类,包:com.google.common.collect.Lists*/
        List<Integer> intList1 = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
        List<List<Integer>> subs1 = Lists.partition(intList1, 3);
        PartialList.printList2(subs1);
        /*2.list为empty*/
        List<Integer> intList2 = new ArrayList<>();
        /*3.分组大于数据*/
        List<List<Integer>> subs2 = Lists.partition(intList2, 10);
        PartialList.printList2(subs2);
        System.out.println("以下是apache的工具类=================================");
        /*正常情况,使用apache工具类分类,包:com.google.common.collect.Lists*/
        List<Integer> intList1apache = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
        List<List<Integer>> subs1apache = ListUtils.partition(intList1apache, 3);
        PartialList.printList2(subs1apache);
        /*list为empty*/
        List<Integer> intList2apache = new ArrayList<>();
        /*2.分组大于数据*/
        List<List<Integer>> subs2apache = ListUtils.partition(intList2apache, 10);
        PartialList.printList2(subs2apache);
    }

    public static void printList2(List<List<Integer>> listList) {
        System.out.println("输出生成list信息:" + listList.size());
        for (List<Integer> sub : listList) {
            System.out.println("进来了");
            for (Integer integer : sub) {
                System.out.println(integer);
            }
        }
        System.out.println("================");
    }
}

执行结果

输出生成list信息:3
进来了
1
2
3
进来了
4
5
6
进来了
7
8
================
输出生成list信息:0
================
以下是apache的工具类=================================
输出生成list信息:3
进来了
1
2
3
进来了
4
5
6
进来了
7
8
================
输出生成list信息:0
================

附上
1.添加jar配置,这个是可以使用的,低版本的或许可以,不保证

	<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
			<version>27.1-jre</version>
	</dependency>
    <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-collections4</artifactId>
            <version>4.0</version>
    </dependency>

2.使用这个分割会遇到在foreach不能remove的情况,具体看文章:https://blog.csdn.net/Mint6/article/details/102875278

猜你喜欢

转载自blog.csdn.net/Mint6/article/details/102875247