Splitting an ArrayList into Multiple Smaller ArrayLists in Java
Dividing an array of a specific length into smaller arrays of a predetermined size is a common task in programming. When dealing with Java ArrayLists, subList(int fromIndex, int toIndex) method proves useful.
The subList() method creates a view of a portion of the original list, starting at the specified fromIndex (inclusive) and ending at the toIndex (exclusive). This view is backed by the original list.
To illustrate its usage, consider an ArrayList of integers:
List<Integer> numbers = new ArrayList<>( Arrays.asList(5, 3, 1, 2, 9, 5, 0, 7) );
Using subList(), we can create smaller views:
List<Integer> head = numbers.subList(0, 4); System.out.println(head); // Prints: [5, 3, 1, 2]
To separate the list into non-view sublists, we can create new lists based on the views:
List<List<Integer>> parts = new ArrayList<>(); final int L = 3; final int N = numbers.size(); for (int i = 0; i < N; i += L) { parts.add(new ArrayList<>(list.subList(i, Math.min(N, i + L)))); }
This results in multiple smaller ArrayLists. However, modifications made to any sublist will be reflected in the original list unless we create an unmodifiable version.
For instance:
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] (unchanged)
The above is the detailed content of How to Split a Java ArrayList into Multiple Smaller ArrayLists?. For more information, please follow other related articles on the PHP Chinese website!