Java8
测试代码:
final AtomicInteger counter = new AtomicInteger(0);
List<Integer> inputList = IntStream.range(1, 99).boxed().collect(Collectors.toList());
int size = 10;
Map<Integer, List<Integer>> map = inputList.stream()
.peek(e-> System.out.println("counter: " + counter))
.collect(Collectors.groupingBy(s -> counter.getAndIncrement() / size));
Collection<List<Integer>> values = map.values();
for (List<Integer> value : values) {
System.out.println(value.size());
}
结果:
...
100
100
100
100
98
apache 工具类
引入工具:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
测试代码:
int targetSize = 100;
List<Integer> largeList = IntStream.range(1, 9999).boxed().collect(Collectors.toList());
List<List<Integer>> lists = ListUtils.partition(largeList, targetSize);
for (List<Integer> list : lists) {
System.out.println(list.size());
}
结果:
...
10
10
10
10
10
8