Java: split a List into two sub-Lists?

Posted by Chris Conway on Stack Overflow See other posts from Stack Overflow or by Chris Conway
Published on 2008-12-18T22:29:37Z Indexed on 2010/04/26 13:23 UTC
Read the original article Hit count: 326

Filed under:
|

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).

© Stack Overflow or respective owner

Related posts about java

Related posts about list