标签 Lists.partition 下的文章

google guava工具类是谷歌提供的一个方便的集合等处理工具

guava的优点:

高效设计良好的API,被Google的开发者设计,实现和使用
遵循高效的java语法实践
使代码更刻度,简洁,简单
节约时间,资源,提高生产力
Guava工程包含了若干被Google的 Java项目广泛依赖 的核心库,例如:

处理能力

集合 [collections]
缓存 [caching]
原生类型支持 [primitives support]
并发库 [concurrency libraries]
通用注解 [common annotations]
字符串处理 [string processing]
I/O 等等。

拆分list示例

 @Test
    public void test1() {
        List<List<Integer>> partitions = Lists.partition(lists, 10);
        for (List<Integer> list : partitions) {
            System.out.println(list);
        }
    }
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>27.1-jre</version>
</dependency>

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.

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