Home > Java > javaTutorial > How to Split an ArrayList into Smaller ArrayLists in Java?

How to Split an ArrayList into Smaller ArrayLists in Java?

DDD
Release: 2024-11-15 03:39:02
Original
474 people have browsed it

How to Split an ArrayList into Smaller ArrayLists in Java?

Splitting an ArrayList into Smaller ArrayLists in Java

Splitting a large ArrayList into multiple smaller ArrayLists is essential in various programming scenarios. To achieve this in Java, you can utilize the subList(int fromIndex, int toIndex) method.

subList Method

The subList method enables you to obtain a portion of the original list. It creates a view of the specified range of elements, starting from fromIndex up to but not including toIndex.

Example Usage

To illustrate, consider the following code:

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

If you require the chopped lists to be non-views, simply create new Lists from the sublists. Here's an 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]]"
Copy after login

This method returns a list of non-view sublists, allowing you to modify them without affecting the original list.

The above is the detailed content of How to Split an ArrayList into 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template