Home > Java > javaTutorial > How to split an ArrayList into multiple smaller ArrayLists in Java?

How to split an ArrayList into multiple smaller ArrayLists in Java?

Barbara Streisand
Release: 2024-11-25 03:22:11
Original
289 people have browsed it

How to split an ArrayList into multiple smaller ArrayLists in Java?

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]"
Copy after login

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

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!

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