You can split the list using Stream
.
static <T> List<List<T>> splitList(List<T> list, int n) {
int size = list.size();
return IntStream.range(0, (size + n - 1) / n)
.map(i -> n * i)
.mapToObj(i -> list.subList(i, Math.min(i + n, size)))
.collect(Collectors.toList());
}
Note that since this uses subList()
, each split list shares the original list.
You can split the array as well.
@SuppressWarnings("unchecked")
static <T> T[][] splitArray(T[] array, int n) {
int size = array.length;
return IntStream.range(0, (size + n - 1) / n)
.map(i -> n * i)
.mapToObj(i -> Arrays.copyOfRange(array, i, Math.min(i + n, size)))
.toArray(i -> (T[][])Array.newInstance(array.getClass(), n));
}
However, this cannot be applied to arrays of primitive types.
Separate implementations are required for primitive types.
For example, for int array:
static int[][] splitArray(int[] array, int n) {
int size = array.length;
return IntStream.range(0, (size + n - 1) / n)
.map(i -> n * i)
.mapToObj(i -> Arrays.copyOfRange(array, i, Math.min(i + n, size)))
.toArray(int[][]::new);
}
test:
public static void main(String[] args) {
List<Integer> list = List.of(7, 3, 9, 10, 5, 6, 8, 13);
System.out.println(splitList(list, 3));
Integer[] array = {7, 3, 9, 10, 5, 6, 8, 13};
System.out.println(Arrays.deepToString(splitArray(array, 3)));
int[] ints = {7, 3, 9, 10, 5, 6, 8, 13};
System.out.println(Arrays.deepToString(splitArray(ints, 3)));
}
output:
[[7, 3, 9], [10, 5, 6], [8, 13]]
[[7, 3, 9], [10, 5, 6], [8, 13]]
[[7, 3, 9], [10, 5, 6], [8, 13]]