Stream工具类,分批执行
复制收展Javapackage com.leixing.util;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
* <p>Title: Stream工具类</p>
*
* <p>Description: Stream工具类</p>
*
* @author luolei
*
* @since:2023/10/27 11:01
*
* @version 1.0
*/
public class StreamUtil {
/**
* 分批次查询
* @param source 查询条件
* @param length 分页大小
* @author tjg
* @return
* @since:2021/12/6 11:00
*/
public static <T> Stream<List<T>> batches(List<T> source, int length) {
if (length <= 0) {
throw new IllegalArgumentException("length = " + length);
}
int size = source.size();
if (size <= 0) {
return Stream.empty();
}
int totalPage = (size - 1) / length;
return IntStream.range(0, totalPage + 1)
.mapToObj(n -> source.subList(n * length, n == totalPage ? size : (n + 1) * length));
}
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
Stream<List<String>> batches = StreamUtil.batches(list, 1);
batches.forEach(subList -> {
System.out.println(subList);
});
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51