java 将一个大list 拆分成多个相同大小的子list 小list
java1.8可以使用stream()流的方法,如下
List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
int chunkSize = 20; //3 ok
AtomicInteger counter = new AtomicInteger();
Collection<List<Integer>> resultList = numbers.stream()
.collect(Collectors.groupingBy(it -> counter.getAndIncrement() / chunkSize))
.values();
System.out.println(resultList);
使用第三方工具类的方法:
- Google Guava has Lists.partition(List list, int size) method (docs)
- Apache Commons Collections has ListUtils.partition(List list, int size) method (docs)
举例说明:
Check out Lists.partition(java.util.List, int) from Google Guava:
Returns consecutive sublists of a list, each of the same size (the final list may be smaller). For example, partitioning a list containing [a, b, c, d, e] with a partition size of 3 yields [[a, b, c], [d, e]] -- an outer list containing two inner lists of three and two elements, all in the original order.