Java8 Stream分割list集合

使用Java8 Stream分割list集合,写好的工具类,可以直接用

package com.example.java8;

import com.example.excel.Student;
import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamUtil {

    /**
     * Description: Java8 Stream分割list集合
     * @param list 集合数据
     * @param splitSize 几个分割一组
     * @return 集合分割后的集合
     */
    public static <T> List<List<T>> splitList(List<T> list, int splitSize) {
        //判断集合是否为空
        if (CollectionUtils.isEmpty(list))
            return Collections.emptyList();
        //计算分割后的大小
        int maxSize = (list.size() + splitSize - 1) / splitSize;
        //开始分割
        return Stream.iterate(0, n -> n + 1)
                .limit(maxSize)
                .parallel()
                .map(a -> list.parallelStream().skip(a * splitSize).limit(splitSize).collect(Collectors.toList()))
                .filter(b -> !b.isEmpty())
                .collect(Collectors.toList());
    }

    public static void main(String[] args) {

        List<Integer> list = new ArrayList<>(1001);
        for (int i = 0; i < 900; i++) {
            list.add(i);
        }
        int splitSize = 100;

        List<List<Integer>> splitList = splitList(list, splitSize);
        for (List<Integer> integers : splitList) {
            integers.forEach(System.out::println);
        }


        List<Student> list1 = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list1.add(new Student(111, "张三asdf", "男"));
            list1.add(new Student(111, "李四asd", "男"));
            list1.add(new Student(111, "王五", "女"));
        }

        List<List<Student>> splitList1 = splitList(list1, splitSize);
        for (List<Student> students : splitList1) {
            students.forEach(e -> System.out.println(e.toString()));
        }
    }
}

你可能感兴趣的:(Java,#,工具类)