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());