大集合分批处理
1:使用stream流分批处理
package com.demo.ddd; import com.google.common.collect.Lists; import org.apache.commons.collections4.ListUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class ObjTest { public static void main(String[] args) { List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); //批次数量 int splitSize = 3; //1:使用stream流分批处理 List<List<Integer>> lists = handleForStream(list, splitSize); System.out.println("stream实现:" + lists); } private static List<List<Integer>> handleForStream(List<Integer> list, int splitSize) { //获取分隔次数 int limit = (list.size() + splitSize - 1) / splitSize; List<List<Integer>> tmpList = new ArrayList<>(); Stream.iterate(0, n -> n + 1).limit(limit).forEach(i -> { tmpList.add(list.stream().skip(i * splitSize).limit(splitSize).collect(Collectors.toList())); }); return tmpList; } }
2:使用工具类-apache
导入依赖
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-collections4</artifactId> <version>4.2</version> </dependency>
代码实现
package com.demo.ddd; import org.apache.commons.collections4.ListUtils; import java.util.Arrays; import java.util.List; public class ObjTest { public static void main(String[] args) { List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); //批次数量 int splitSize = 3; //使用工具类实现-apache List<List<Integer>> partition = ListUtils.partition(list, splitSize); System.out.println("apache实现:" + partition); } }
3:使用工具类-guava
导入依赖
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>15.0</version> </dependency>
代码实现
package com.demo.ddd; import com.google.common.collect.Lists; import java.util.Arrays; import java.util.List; public class ObjTest { public static void main(String[] args) { List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); //批次数量 int splitSize = 3; //使用工具类-guava List<List<Integer>> partition1 = Lists.partition(list, splitSize); System.out.println("guava实现:" + partition1); } }
全部统一执行后打印结果如下: