Java: split a List into two sub-Lists?

后端 未结 14 1535
执笔经年
执笔经年 2020-12-08 02:29

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 nece

14条回答
  •  眼角桃花
    2020-12-08 02:51

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

提交回复
热议问题