介绍几种List集合分批操作的工具

• 创建集合

``````List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);

//计算页数
int limit = (list.size() + MAX_NUMBER - 1) / MAX_NUMBER;``````
• 使用流对list进行分割

``````/* ----------------------使用流对list进行分割--------------------------*/
List<List<Integer>> subList = new ArrayList<>();
Stream.iterate(0, n -> n + 1).limit(limit).forEach(i ->
);
System.out.println(subList);

/* ----------------------使用流对list进行分割--------------------------*/
List<List<Integer>> subList0 = 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(subList0);``````
• 使用guava对list进行分割

``````List<List<Integer>> supList1 = Lists.partition(list, MAX_NUMBER);
System.out.println(supList1);``````
• commons-collections4方式

``````List<List<Integer>> subList2 = ListUtils.partition(list, MAX_NUMBER);
System.out.println(subList2);``````
• 输出结果

``````[[1, 2, 3], [4, 5, 6], [7, 8, 9], [0]]
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [0]]
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [0]]
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [0]]``````

19 声望
3 粉丝
0 条评论