java8 Stream 大数据量List分批处理
//按每3个一组分割
private static final Integer MAX_NUMBER = 3;
/**
* 计算切分次数
*/
private static Integer countStep(Integer size) {
return (size + MAX_NUMBER - 1) / MAX_NUMBER;
}
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
int limit = countStep(list.size());
//方法一:使用流遍历操作
List<List<Integer>> mglist = new ArrayList<>();
Stream.iterate(0, n -> n + 1).limit(limit).forEach(i -> {
mglist.add(list.stream().skip(i * MAX_NUMBER).limit(MAX_NUMBER).collect(Collectors.toList()));
});
System.out.println(mglist);
//方法二:获取分割后的集合
List<List<Integer>> splitList = Stream.iterate(0, n -> n + 1).limit(limit).parallel().map(a -> list.stream().skip(a * MAX_NUMBER).limit(MAX_NUMBER).parallel().collect(Collectors.toList())).collect(Collectors.toList());
System.out.println(splitList);
}
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
使用google guava对List进行分割
//使用guava对list进行分割
List<User> users = userService.findAll();
//按每50个一组分割
List<List<User>> parts = Lists.partition(users, 50);
parts.stream().forEach(list -> {
process(list);
});
1
2
3
4
5
6
7
使用apache common collection
List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
List<List<Integer>> subs = ListUtils.partition(intList, 3);
1
2
java 手写将一个List等分成n个list
public static <T> List<List<T>> averageAssign(List<T> source, int n) {
List<List<T>> result = new ArrayList<>();
//(先计算出余数)
int remainder = source.size() % n;
//然后是商
int number = source.size() / n;
//偏移量
int offset = 0;
for (int i = 0; i < n; i++) {
List<T> value;
if (remainder > 0) {
value = source.subList(i * number + offset, (i + 1) * number + offset + 1);
remainder--;
offset++;
} else {
value = source.subList(i * number + offset, (i + 1) * number + offset);
}
result.add(value);
}
return result;
}
-
int pageSize = 3;
-
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
-
List<List<Integer>> collect = IntStream.range(0, (list.size() + pageSize - 1) / pageSize)
-
.map(pageNum -> pageNum * pageSize).parallel()
-
.mapToObj(i -> list.stream().skip(i).limit(pageSize).collect(Collectors.toList()))
-
.collect(Collectors.toList());
-
System.out.println(JSON.toJSONString(collect));
-
//运行结果
-
//[[1,2,3],[4,5,6],[7]]
————————————————
版权声明:本文为CSDN博主「zhaoyang10」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/fzy629442466/article/details/84765070