大集合拆分成多个小集合

文章目录

  • 1. 场景
  • 2. 拆分集合方法(写了三种)
  • 3. 格式化打印方法

1. 场景

在数据库批量操作时,有可能数据量过大,不能一次性操作,所以需要将大集合拆分为多个小集合进行多次操作

2. 拆分集合方法(写了三种)

import com.google.common.collect.Lists;
import com.xin.demo.fastjsondemo.FastJsonFormatPrintUtils;
import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class PartitionListDemo {

    private static final int PARTITION_SIZE = 10;
    
    public static void main(String[] args) {

        // 大集合
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 33; i++) {
            list.add("xinliushijian" + i);
        }

        // 方法1 guava工具
        List<List<String>> partitionList = Lists.partition(list, PARTITION_SIZE);
        FastJsonFormatPrintUtils.formatPrint(partitionList);
        System.out.println("===============");

        // 方法2 stream流实现
        List<List<String>> partitionList1 = partList1(list, PARTITION_SIZE);
        FastJsonFormatPrintUtils.formatPrint(partitionList1);

        // 方法3 普通方法实现
        partList2(list, PARTITION_SIZE);
    }

    public static <T> List<List<T>> partList1(List<T> list, int size) {
        if (CollectionUtils.isEmpty(list) || size < 1) {
            return new ArrayList<>();
        }

        List<List<T>> partList = IntStream.range(0, list.size())
                .boxed()
                .collect(Collectors.groupingBy(index -> index / size))
                .values()
                .stream()
                .map(indices -> indices.stream().map(list::get).collect(Collectors.toList()))
                .collect(Collectors.toList());

        return partList;
    }

    public static <T> List<List<T>> partList2(List<T> list, int size) {
        if (CollectionUtils.isEmpty(list) || size < 1) {
            return new ArrayList<>();
        }

        List<List<T>> allPartList = new ArrayList<>();

        for (int i = 0; i < list.size(); i+=size) {
            if (i + size > list.size()) {
                size  = list.size() - i;
            }

            List<T> parList = list.subList(i, i + size);
            allPartList.add(parList);
        }
        FastJsonFormatPrintUtils.formatPrint(allPartList);

        return allPartList;
    }

}

3. 格式化打印方法

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.JSON;

public class FastJsonFormatPrintUtils {
    public static void formatPrint(Object object) {
        String pretty = JSON.toJSONString(object, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteDateUseDateFormat);

        System.out.println(pretty);
    }

}

你可能感兴趣的:(Java基础知识,java)