Efficient way to divide a list into lists of n size

前端 未结 14 1197
无人共我
无人共我 2020-11-27 16:59

I have an ArrayList, which I want to divide into smaller Lists of n size, and perform an operation on each. My current method of doing this is

implemented with Array

相关标签:
14条回答
  • 2020-11-27 17:42

    If you are dealing with arrays, you can use System.arraycopy() for that.

     int[] a = {1,2,3,4,5};
    
     int[] b = new int[2];
     int[] c = new int[3];
    
     System.arraycopy(a, 0, b, 0, 2); // b will be {1,2}
     System.arraycopy(a, 2, c, 0, 3); // c will be {3,4,5}
    
    0 讨论(0)
  • 2020-11-27 17:42

    Here is a way to partition a List into an array of sublists, which ensures all but the last sublist have equal number of elements:

    static <T> List<T>[] split(List<T> source, int numPartitions) {
        if (numPartitions < 2)
            return new List[]{source};
    
        final int sourceSize = source.size(),
            partitions = numPartitions > sourceSize ? sourceSize: numPartitions,
            increments = sourceSize / partitions;
    
        return IntStream.rangeClosed(0, partitions)
            .mapToObj(i -> source.subList(i*increments, Math.min((i+1)*increments, sourceSize)))
            .toArray(List[]::new);
    }
    

    If you want to guarantee numPartitions array size then you want:

    static <T> List<T>[] split(List<T> source, int numPartitions) {
        if (numPartitions < 2)
            return new List[]{source};
    
        final int sourceSize = source.size(),
            partitions = numPartitions > sourceSize ? sourceSize: numPartitions,
            increments = sourceSize / partitions;
    
        return IntStream.range(0, partitions)
            .mapToObj(i -> source.subList(i*increments, i == partitions-1 ? sourceSize : (i+1)*increments))
            .toArray(List[]::new);
    }
    
    0 讨论(0)
提交回复
热议问题