首頁 > Java > java教程 > 如何在Java中有效率地將ArrayList拆分為多個子清單?

如何在Java中有效率地將ArrayList拆分為多個子清單?

DDD
發布: 2024-11-15 08:34:02
原創
681 人瀏覽過

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.

以上是如何在Java中有效率地將ArrayList拆分為多個子清單?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板