You have probably faced a few times a situation where you had to divide n-size list to lists of m-size. Something like:
[1,2,3,4,5,6,7] -> [[1,2], [3,4], [5,6], [7]]
You won’t find a simple method in Java SDK for such operation, although there are some utility methods in 3rd party libraries, e.g. Lists.partition(List list, int size) in Guava or ListUtils.partition(List list, int size) in Apache Commons Collections. But what if you don’t have these libraries added to your project and you don’t want to add them just for a single utility method?
Use Java 8 Stream API
Luckily you can utilize Java 8 Stream API to do same thing:
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
final class Java8StreamPartitionExample {
public static void main(String[] args) {
final List<Integer> list = Arrays.asList(1,2,3,4,5,6,7);
System.out.println(partition(list, 2)); // [[1, 2], [3, 4], [5, 6], [7]]
System.out.println(partition(list, 3)); // [[1, 2, 3], [4, 5, 6], [7]]
}
private static <T> Collection<List<T>> partition(List<T> list, int size) {
final AtomicInteger counter = new AtomicInteger(0);
return list.stream()
.collect(Collectors.groupingBy(it -> counter.getAndIncrement() / size))
.values();
}
}
本文介绍如何使用Java8 Stream API将任意大小的列表分割成固定大小的子列表,提供了一个实用的方法实现,避免了引入第三方库的依赖。

6784

被折叠的 条评论
为什么被折叠?



