Java: how can I split an ArrayList in multiple small ArrayLists?
Here is an example of how you can split an ArrayList into multiple smaller ArrayLists
in Java:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
int size = 2;
List<List<Integer>> subLists = new ArrayList<>();
for (int i = 0; i < list.size(); i += size) {
subLists.add(list.subList(i, Math.min(i + size, list.size())));
}
System.out.println(subLists);
}
}
This will output the following:
[[1, 2], [3, 4], [5]]
Note that the subList
method returns a view of the original list, so any changes to the sublists will be reflected in the original list. If you want to create a new list with the elements of the sublist, you can use the new ArrayList<>(subList)
constructor.