I have an ArrayList, which I want to divide into smaller Lists of n size, and perform an operation on each. My current method of doing this is
implemented with Array
If you are dealing with arrays, you can use System.arraycopy() for that.
int[] a = {1,2,3,4,5};
int[] b = new int[2];
int[] c = new int[3];
System.arraycopy(a, 0, b, 0, 2); // b will be {1,2}
System.arraycopy(a, 2, c, 0, 3); // c will be {3,4,5}
Here is a way to partition a List into an array of sublists, which ensures all but the last sublist have equal number of elements:
static <T> List<T>[] split(List<T> source, int numPartitions) {
if (numPartitions < 2)
return new List[]{source};
final int sourceSize = source.size(),
partitions = numPartitions > sourceSize ? sourceSize: numPartitions,
increments = sourceSize / partitions;
return IntStream.rangeClosed(0, partitions)
.mapToObj(i -> source.subList(i*increments, Math.min((i+1)*increments, sourceSize)))
.toArray(List[]::new);
}
If you want to guarantee numPartitions
array size then you want:
static <T> List<T>[] split(List<T> source, int numPartitions) {
if (numPartitions < 2)
return new List[]{source};
final int sourceSize = source.size(),
partitions = numPartitions > sourceSize ? sourceSize: numPartitions,
increments = sourceSize / partitions;
return IntStream.range(0, partitions)
.mapToObj(i -> source.subList(i*increments, i == partitions-1 ? sourceSize : (i+1)*increments))
.toArray(List[]::new);
}