1、构建一个lis集合类
private static List<Integer> lists = new ArrayList<Integer>(); @Before public void test0() { for (int i = 0; i <= 101; i++) { lists.add(i); } }
2、使用google guava工具类
@Test public void test1() { List<List<Integer>> partitions = Lists.partition(lists, 10); for (List<Integer> list : partitions) { System.out.println(list); } }
pom.xml文件
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>27.1-jre</version> </dependency>
3、使用apache collection工具类
@Test public void test2() { List<List<Integer>> partitions = ListUtils.partition(lists, 10); for (List<Integer> list : partitions) { System.out.println(list); } }
pom.xml文件
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-collections4</artifactId> <version>4.3</version> </dependency>
3、使用java8 stream分割
@Test public void test3() { // 方法一: List<List<Integer>> partitions = partition(lists, 10); for (List<Integer> list : partitions) { System.out.println(list); } // 方法二: List<List<Integer>> partitions3 = partition3(lists, 10); for (List<Integer> list : partitions3) { System.out.println(list); } } // 使用流遍历操作 private static <T> List<List<T>> partition(final List<T> list, final int size) { Integer limit = (list.size() + size - 1) / size; List<List<T>> mglist = new ArrayList<List<T>>(); Stream.iterate(0, n -> n + 1).limit(limit).forEach(i -> { mglist.add(list.stream().skip(i * size).limit(size).collect(Collectors.toList())); }); return mglist; } // 使用并行流处理 private static <T> List<List<T>> partition3(final List<T> list, final int size) { Integer limit = (list.size() + size - 1) / size; List<List<T>> splitList = Stream.iterate(0, n -> n + 1).limit(limit).parallel() .map(a -> list.stream().skip(a * size).limit(size).parallel().collect(Collectors.toList())) .collect(Collectors.toList()); return splitList; }
4、使用纯java手写
@Test public void test4() { List<List<Integer>> partitions = partitions(lists, 10); for (List<Integer> list : partitions) { System.out.println(list); } } private static <T> List<List<T>> partitions(final List<T> list, final int size) { List<List<T>> result = new ArrayList<List<T>>(); final int listSize = list.size(); for (int i = 0; i < listSize; i += size) { List<T> subList = null; if (i + size > listSize) { subList = list.subList(i, i + listSize - i); } else { subList = list.subList(i, i + size); } result.add(subList); } return result; }