The following will work for any group size from 1 to the size of the list
. If the group size does not evenly divided the list size then the remainder will be put into their own group.
Also, the extra map(ArrayList::new)
ensures the sublist is put in its own list. Otherwise, changing the original list entries will also change the sublist entries.
int gsize = 2;
List<Integer> mylist =
Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
List<List<Integer>> subLists = IntStream
.iterate(0, i -> i < mylist.size(),
i -> i + gsize)
.mapToObj(i -> mylist.subList(i,
(i + gsize <= mylist.size()) ?
i + gsize : mylist.size()))
.map(ArrayList::new)
.collect(Collectors.toList());
System.out.println(subLists);
Prints
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]]
If the group size was 5, the new list would look like the following:
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12]]