public static void main(String[] args) {
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 6, 5, 4, 7, 8, 5, 2, 14, 56);
List<List<Integer>> chopped = chopped(integers, 5);
for (List<Integer> integerList : chopped) {
System.out.println(integerList);
}
}
// chops a list into non-view sublists of length L
static <T> List<List<T>> chopped(List<T> list, final int L) {
List<List<T>> parts = new ArrayList<>();
final int N = list.size();
for (int i = 0; i < N; i += L) {
parts.add(new ArrayList<>(
list.subList(i, Math.min(N, i + L)))
);
}
return parts;
}
输出结果:[1, 2, 3, 4, 5]
[6, 7, 8, 9, 6]
[5, 4, 7, 8, 5]
[2, 14, 56]