Ber*_*eri 19 java partitioning java-8
是否可以将纯Jdk8中的List分区为相等的块(子列表).
我知道可以使用Guava Lists类,但是我们可以使用纯Jdk吗?我不想在我的项目中添加新的jar,仅用于一个用例.
解决方案:
tagir-valeev提出了迄今为止最好的解决方案:
我还发现了其他三种可能性,但它们只适用于少数情况:
1.Collectors.partitioningBy()将列表拆分为2个子列表 - 如下所示:
intList.stream().collect(Collectors.partitioningBy(s -> s > 6));
List<List<Integer>> subSets = new ArrayList<List<Integer>>(groups.values());
Run Code Online (Sandbox Code Playgroud)
2.Collectors.groupingBy()将我们的列表拆分为多个分区:
Map<Integer, List<Integer>> groups =
intList.stream().collect(Collectors.groupingBy(s -> (s - 1) / 3));
List<List<Integer>> subSets = new ArrayList<List<Integer>>(groups.values());
Run Code Online (Sandbox Code Playgroud)
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());
Run Code Online (Sandbox Code Playgroud)
Rob*_*ert 21
这可以使用以下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));
}
Run Code Online (Sandbox Code Playgroud)
小智 7
尝试使用此代码,它使用 Java 8:
public static Collection<List<Integer>> splitListBySize(List<Integer> intList, int size) {
if (!intList.isEmpty() && size > 0) {
final AtomicInteger counter = new AtomicInteger(0);
return intList.stream().collect(Collectors.groupingBy(it -> counter.getAndIncrement() / size)).values();
}
return null;
}
Run Code Online (Sandbox Code Playgroud)