将一个列表(集合)拆分为多个指定大小的子列表(集合)(List<T>)


tips*

如何将一个集合拆分为多个给定大小的子集


一、Apache Commons Collections

1.使用 Apache Commons Collections 对列表进行分区

代码如下():

List<Integer>intList =Lists.newArrayList(1,2,3,4,5,6,7,7,7,7,7,7,7,8);
List<List<Integer>> subLists = ListUtils.partition(intList,4)

二、使用 Guava 对列表进行分区

1.Guava 通过Lists.partition 操作将 List 划分为指定大小

代码如下:


List<Integer> intList = Lists.newArrayList(1,2,3,4,5,6,7,7,7,7,7,8);

List<List<Integer>> subLists = Lists.partition(intList,4)

2.使用 Guava 对集合进行分区

代码如下:


Collection<Integer> intCollection = Lists.newArrayList(1, 2, 3, 5, 6, 7, 89, 32, 34, 53, 64, 90);

Iterable<List<Integer>> subLists = Iterables.partition(intCollection, 3);

三、使用Java8对列表进行分区

1.Collectors.partitioningBy() 将列表拆分

代码如下:


List<Integer> intList = Lists.newArrayList(11, 21, 32, 42, 56,0, 61, 76, 81);

Map<Boolean, List<Integer>> groups = intList.stream().collect(Collectors.partitioningBy(s -> s > 40));

List<List<Integer>> subLists = new ArrayList<List<Integer>>(groups.values());

2.使用分隔符 将列表拆分

代码如下:


List<Integer> intList = Lists.newArrayList(11, 21, 32, 0, 42, 56, 61, 0, 76, 81, 90, 80);

int[] indexes = Stream.of(IntStream.of(-1),IntStream.range(0,intList.size()).filter(i>intList.get(i)==0),Intstream.of(intList.size()))flatMapToInt(s ->s).toArray();

List<List<Integer>> subLists = IntStream.range(0,indexes.length-1).mapToObj(i ->intList.subList(indexes[i]+1,indexes[i + 1])).collect(Collectors.toList());

此处使用“0”作为分割符,获取字符索引,根据索引进行分割获取子列表

  • 7
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值