Java:将List拆分为两个子列表?

Chr*_*way 36 java list

在List中将List拆分为两个子列表的最简单,最标准和/或最有效的方法是什么?改变原始列表是可以的,因此不需要复制.方法签名可以是

/** 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);
Run Code Online (Sandbox Code Playgroud)

[EDIT] List.subList返回原始列表中的视图,如果修改了原始列表,该视图将变为无效.所以split不能使用,subList除非它也省略了原始参考(或者,如在Marc Novakowski的答案中,使用subList但立即复制结果).

Law*_*Dol 53

快速半伪代码:

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
Run Code Online (Sandbox Code Playgroud)

它使用标准的List实现方法,并避免所有在循环中运行.clear()方法也将使用removeRange()大多数列表的内部并且效率更高.


alt*_*ano 31

您可以使用常用实用程序,例如Guava库:

import com.google.common.collect.Lists;
import com.google.common.math.IntMath;
import java.math.RoundingMode;

int partitionSize = IntMath.divide(list.size(), 2, RoundingMode.UP);
List<List<T>> partitions = Lists.partition(list, partitionSize);
Run Code Online (Sandbox Code Playgroud)

结果是两个列表的列表 - 不完全符合您的规范,但如果需要,您可以轻松地进行调整.


Bra*_*tte 5

重复使用Marc的解决方案,这个解决方案使用一个for循环来节省一些调用list.size():

<T> List<T> split(List<T> list, int i) {
    List<T> x = new ArrayList<T>(list.subList(i, list.size()));
    // Remove items from end of original list
    for (int j=list.size()-1; j>i; --j)
        list.remove(j);
    return x;
}
Run Code Online (Sandbox Code Playgroud)