How can I take a Java list and split it into smaller lists of size n
in Java using streams?
In JavaScript, I'd use the reduce()
function and do something like this:
const n = 3;
const sublists = [1,2,3,4,5,6,7,8,9,0]
.reduce((r, i) => {
r[r.length - 1].length == n
? r.push([i])
: r[r.length - 1].push(i);
return r;
}, [[]]);
console.log(sublists);
I'm trying to do that with a Java stream, but I can't seem to figure out how to get it to let me use an ArrayList<ArrayList<Integer>>
as my initial value and then add the lists. I'm a little confused how the combinator and accumulator play in to let me use them, or even if reduce()
is the best approach for Java.