自学内容网 自学内容网

将List切割为多个指定长度的多个List

参考:

手写1

private List<List<String>> splitList(List<String> list, int listSize){
 if (null === list || 0 === listSize) {
return new ArrayList();
 }
     int length = list.size();
     int num = ( length + listSize- 1 )/listSize; 
     List<List<String>> newList = new ArrayList<>(num);
     for (int i = 0; i < num; i++) {
         int fromIndex = i * listSize;
         int toIndex = (i+1) * listSize< length ? ( i+1 ) * listSize: length ;
         newList.add(list.subList(fromIndex, toIndex)) ;
     }
     return  newList ;
 }

手写2

    public static <T> List<List<T>> splitList(List<T> list, int splitSize) {
        List<List<T>> subLists = new ArrayList<>();
    
        for (int i = 0; i < list.size(); i += splitSize) {
            int end = Math.min(i + splitSize, list.size());
            subLists.add(list.subList(i, end));
        }
    
        return subLists;
    }

手写3

    public static <T> List<List<T>> splitList(List<T> list, int splitSize) {
        return IntStream.range(0, (list.size() + splitSize - 1) / splitSize)
                .mapToObj(i -> list.subList(i * splitSize, Math.min((i + 1) * splitSize, list.size())))
                .collect(Collectors.toList());
    }

Guava

    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>12.0.1</version>
    </dependency>
Lists.partition(list, listSize)

apache的collections4

    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-collections4</artifactId>
      <version>4.4</version>
    </dependency>
ListUtils.partition(OLD_LIST, 3);

hutool

    <dependency>
      <groupId>cn.hutool</groupId>
      <artifactId>hutool-all</artifactId>
      <version>5.7.14</version>
    </dependency>
ListUtil.partition(OLD_LIST, 3);

原文地址:https://blog.csdn.net/qq_36254947/article/details/140151526

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!