Splitting an ArrayList into Multiple Smaller ArrayLists in Java
In Java, splitting an ArrayList into multiple smaller ArrayLists of a specified size requires a solution that allows for efficient portioning and potentially creates non-view sublists.
Using subList()
One approach is to utilize the subList(int fromIndex, int toIndex) method to obtain a view of a portion of the original list. This method does not create a new list but rather provides a reference to a segment within the existing ArrayList.
Example:
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
However, if you need the chopped lists to be independent and not a view of the original list, you can create a new ArrayList from the subList.
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]]" parts.get(0).add(-1); System.out.println(parts); // prints "[[5, 3, 1, -1], [2, 9, 5], [0, 7]]" System.out.println(numbers); // prints "[5, 3, 1, 2, 9, 5, 0, 7]" (unmodified!)
The above is the detailed content of How to split an ArrayList into multiple smaller ArrayLists in Java?. For more information, please follow other related articles on the PHP Chinese website!