Java: split a List into two sub-Lists?

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.


You can use common utilities, like Guava library:

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

The result is a list of two lists - not quite by your spec, but you can easily adapt, if needed.

Tags:

Java

List