Home > Java > javaTutorial > How to Split a Java ArrayList into Multiple Smaller ArrayLists?

How to Split a Java ArrayList into Multiple Smaller ArrayLists?

Mary-Kate Olsen
Release: 2024-11-19 04:33:02
Original
434 people have browsed it

How to Split a Java ArrayList into Multiple Smaller ArrayLists?

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)
);
Copy after login

Using subList(), we can create smaller views:

List<Integer> head = numbers.subList(0, 4);
System.out.println(head); // Prints: [5, 3, 1, 2]
Copy after login

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))));
}
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template