Java8

测试代码:

  1. final AtomicInteger counter = new AtomicInteger(0);
  2. List<Integer> inputList = IntStream.range(1, 99).boxed().collect(Collectors.toList());
  3. int size = 10;
  4. Map<Integer, List<Integer>> map = inputList.stream()
  5. .peek(e-> System.out.println("counter: " + counter))
  6. .collect(Collectors.groupingBy(s -> counter.getAndIncrement() / size));
  7. Collection<List<Integer>> values = map.values();
  8. for (List<Integer> value : values) {
  9. System.out.println(value.size());
  10. }

结果:

  1. ...
  2. 100
  3. 100
  4. 100
  5. 100
  6. 98

apache 工具类

引入工具:

  1. <dependency>
  2. <groupId>org.apache.commons</groupId>
  3. <artifactId>commons-collections4</artifactId>
  4. <version>4.4</version>
  5. </dependency>

测试代码:

  1. int targetSize = 100;
  2. List<Integer> largeList = IntStream.range(1, 9999).boxed().collect(Collectors.toList());
  3. List<List<Integer>> lists = ListUtils.partition(largeList, targetSize);
  4. for (List<Integer> list : lists) {
  5. System.out.println(list.size());
  6. }

结果:

  1. ...
  2. 10
  3. 10
  4. 10
  5. 10
  6. 10
  7. 8