Home >Java >javaTutorial >How to Efficiently Split an ArrayList into Multiple Sublists in Java?
Splitting an ArrayList into Multiple Sublists
In Java, you can efficiently partition an ArrayList into smaller, equally sized sublists. This is useful in scenarios where you need to process or manage data in bite-sized chunks.
Using subList() to Create Views
The subList() method of the ArrayList class allows you to obtain a view of a portion of the original list within the specified range. Calls to subList() do not create a new list but return a view into the existing list. Any changes made to the sublist are reflected in the original list and vice versa.
List<Integer> numbers = new ArrayList<>(Arrays.asList(5, 3, 1, 2, 9, 5, 0, 7)); List<Integer> head = numbers.subList(0, 4); // View from index 0 to index 3 (exclusive) List<Integer> tail = numbers.subList(4, 8); // View from index 4 to index 7 (exclusive)
Creating Non-View Sublists
If you require the sublists to be independent of the original list, you can explicitly create new ArrayList objects from the sublist views.
List<List<Integer>> chopped = new ArrayList<>(); for (int i = 0; i < numbers.size(); i += L) { List<Integer> sublist = new ArrayList<>( numbers.subList(i, Math.min(numbers.size(), i + L)) ); chopped.add(sublist); }
This approach creates deep copies of the sublist, ensuring that changes to the chopped sublists do not affect the original list.
Example Usage
Consider a List of integers called numbers containing [5, 3, 1, 2, 9, 5, 0, 7]. You can split this list into three sublists of size 3 using the following code:
List<List<Integer>> choppedLists = chopped(numbers, 3);
The choppedLists variable will now contain three lists: [[5, 3, 1], [2, 9, 5], [0, 7]]. You can further modify these sublists without altering the original numbers list.
The above is the detailed content of How to Efficiently Split an ArrayList into Multiple Sublists in Java?. For more information, please follow other related articles on the PHP Chinese website!