Java 8分区列表 [英] Java 8 partition list
问题描述
是否可以将纯Jdk8中的List分成相等的块(子列表)。
Is it possible to partition a List in pure Jdk8 into equal chunks (sublists).
我知道可以使用Guava 列表类,但是我们可以使用纯Jdk吗?我不想在我的项目中添加新的jar,仅用于一个用例。
I know it is possible using Guava Lists class, but can we do it with pure Jdk? I don't want to add new jars to my project, just for one use case.
SOLUTONS :
我还找到了其他三个可能性,但它们只适用于少数情况:
I have also found three other possibilities, but they are ment for only few cases:
1.Collectors.partitioningBy()将列表拆分为2个子列表 - 如下所示:
1.Collectors.partitioningBy() to split the list into 2 sublists – as follows:
intList.stream().collect(Collectors.partitioningBy(s -> s > 6));
List<List<Integer>> subSets = new ArrayList<List<Integer>>(groups.values());
2.Collectors.groupingBy()将我们的列表拆分为多个分区:
2.Collectors.groupingBy() to split our list to multiple partitions:
Map<Integer, List<Integer>> groups =
intList.stream().collect(Collectors.groupingBy(s -> (s - 1) / 3));
List<List<Integer>> subSets = new ArrayList<List<Integer>>(groups.values());
3.按分隔符分隔:
List<Integer> intList = Lists.newArrayList(1, 2, 3, 0, 4, 5, 6, 0, 7, 8);
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>> subSets =
IntStream.range(0, indexes.length - 1)
.mapToObj(i -> intList.subList(indexes[i] + 1, indexes[i + 1]))
.collect(Collectors.toList());
推荐答案
使用<$ c $可以轻松完成c> subList()方法:
List<String> collection = new ArrayList(21);
// fill collection
int chunkSize = 10;
List<List<String>> lists = new ArrayList<>();
for (int i=0; i<collection.size(); i+= chunkSize) {
int end = Math.min(collection.size(), i + chunkSize);
lists.add(collection.subList(i, end));
}
这篇关于Java 8分区列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!