Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: split a List into two sub-Lists?

Tags:

java

list

What's the simplest, most standard, and/or most efficient way to split a List into two sub-Lists in Java? It's OK to mutate the original List, so no copying should be necessary. The method signature could be

/** Split a list into two sublists. The original list will be modified to  * have size i and will contain exactly the same elements at indices 0   * through i-1 as it had originally; the returned list will have size   * len-i (where len is the size of the original list before the call)   * and will have the same elements at indices 0 through len-(i+1) as   * the original list had at indices i through len-1.  */ <T> List<T> split(List<T> list, int i); 

[EDIT] List.subList returns a view on the original list, which becomes invalid if the original is modified. So split can't use subList unless it also dispenses with the original reference (or, as in Marc Novakowski's answer, uses subList but immediately copies the result).

like image 333
Chris Conway Avatar asked Dec 18 '08 22:12

Chris Conway


People also ask

How do you split an ArrayList?

import org. List<Integer> inputList = new ArrayList(Arrays. asList(100, 101, 102, 103, 104, 105)); /* Change the value of chunkSize to get desired number of elements in each of the partitionedList */ int chunkSize = 5; List<List<Integer>> partitionedList = ListUtils. partition(inputList, chunkSize);

What is partitioning in Java?

java. In number theory, * a partition of N is a way to write it as a sum of positive integers. * Two sums that differ only in the order of their terms are considered * the same partition.


1 Answers

Quick semi-pseudo code:

List sub=one.subList(...); List two=new XxxList(sub); sub.clear(); // since sub is backed by one, this removes all sub-list items from one 

That uses standard List implementation methods and avoids all the running around in loops. The clear() method is also going to use the internal removeRange() for most lists and be much more efficient.

like image 160
Lawrence Dol Avatar answered Sep 23 '22 23:09

Lawrence Dol