Java8 Stream分割list集合

发布于:2021-12-02 23:14:15

使用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 List> splitList(List 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 list = new ArrayList<>(1001);
for (int i = 0; i < 900; i++) {
list.add(i);
}
int splitSize = 100;

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


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

相关推荐

最新更新

猜你喜欢