您的位置:首页 > 娱乐 > 明星 > 将List切割为多个指定长度的多个List

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

2024/12/23 14:45:52 来源:https://blog.csdn.net/qq_36254947/article/details/140151526  浏览:    关键词:将List切割为多个指定长度的多个List

参考:

  • https://blog.csdn.net/baidu_41480640/article/details/122507018
  • https://blog.csdn.net/H1767410/article/details/138333350
  • https://blog.51cto.com/u_16213352/7632003
  • https://blog.csdn.net/2301_82243396/article/details/137900249

手写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);

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com