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.

标签: Lists.partition, list拆分


阿里云优惠主机

仅有一条评论

  1. repostone repostone

    非技术的路过。https://repostone.home.blog/

添加新评论

免责声明
本博客部分内容来自于互联网,不代表作者的观点和立场,如若侵犯到您的权益,请联系[email protected]。我们会在24小时内进行删除。