Splitting an ArrayList into Smaller ArrayLists in Java
Splitting a large ArrayList into multiple smaller ArrayLists is essential in various programming scenarios. To achieve this in Java, you can utilize the subList(int fromIndex, int toIndex) method.
subList Method
The subList method enables you to obtain a portion of the original list. It creates a view of the specified range of elements, starting from fromIndex up to but not including toIndex.
Example Usage
To illustrate, consider the following code:
List<Integer> numbers = new ArrayList<>(Arrays.asList(5, 3, 1, 2, 9, 5, 0, 7)); List<Integer> head = numbers.subList(0, 4); List<Integer> tail = numbers.subList(4, 8); System.out.println(head); // prints "[5, 3, 1, 2]" System.out.println(tail); // prints "[9, 5, 0, 7]"
Creating Non-View Sublists
If you require the chopped lists to be non-views, simply create new Lists from the sublists. Here's an example:
// Chops a list into non-view sublists of length L static <T> List<List<T>> chopped(List<T> list, final int L) { List<List<T>> parts = new ArrayList<>(); final int N = list.size(); for (int i = 0; i < N; i += L) { parts.add(new ArrayList<>(list.subList(i, Math.min(N, i + L)))); } return parts; } List<Integer> numbers = Collections.unmodifiableList(Arrays.asList(5, 3, 1, 2, 9, 5, 0, 7)); List<List<Integer>> parts = chopped(numbers, 3); System.out.println(parts); // prints "[[5, 3, 1], [2, 9, 5], [0, 7]]"
This method returns a list of non-view sublists, allowing you to modify them without affecting the original list.
The above is the detailed content of How to Split an ArrayList into Smaller ArrayLists in Java?. For more information, please follow other related articles on the PHP Chinese website!