My question is very straightforward... I have a list of elements and I want to make subgroups of certain amount... Could that be done in Java with an API ?... Or I should start playing with counters etc...
Asked
Active
Viewed 139 times
-1
-
Does this answer your question? [Java: how can I split an ArrayList in multiple small ArrayLists?](https://stackoverflow.com/questions/2895342/java-how-can-i-split-an-arraylist-in-multiple-small-arraylists) – Tobias Feb 09 '21 at 18:51
-
1You say your question is straightforward but I disagree. It is vague and not precise. It is lacking details and is generally unclear. Downvoted and voting to close because of that. Please see [ask]. – Zabuzard Feb 09 '21 at 18:52
1 Answers
2
Not really necessary to find an API just for this.
Here's a simple method to do what you want:
public static <T> List<List<T>> splitList(int groupSize, List<T> list) {
List<List<T>> subLists = new ArrayList<>();
for (int i = 0; i < list.size();) {
subLists.add(list.subList(i, i = Math.min(i + groupSize, list.size())));
}
return subLists;
}
public static void main(String[] args) throws Exception {
List<Integer> list = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
List<List<Integer>> subLists = splitList(3, list);
System.out.println(subLists);
// prints [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13]]
}

xtratic
- 4,600
- 2
- 14
- 32