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 don't want to use a library, here's my solution
1.To partition in N equal parts:
private List> nPartition(List objs, final int N) {
return new ArrayList<>(IntStream.range(0, objs.size()).boxed().collect(
Collectors.groupingBy(e->e%N,Collectors.mapping(e->objs.get(e), Collectors.toList())
)).values());
}
2. To partition in sets of N items:
private List> nPartition(List objs, final int N) {
return new ArrayList<>(IntStream.range(0, objs.size()).boxed().collect(
Collectors.groupingBy(e->e/N,Collectors.mapping(e->objs.get(e), Collectors.toList())
)).values());
}
In action here: https://ideone.com/QiQnbE