繁体   English   中英

将array_chunk从PHP转换为Java

[英]convert array_chunk from php to java

我的PHP代码是:

$splitArray = array_chunk($theArray,ceil(count($theArray) / 2),true);

php的array_chunk函数将数组拆分为您指定大小的块。 您可以使用Arrays.copyOfRange在Java中执行此操作,并传入起点和终点。 这是一些示例代码:

/**
 * Chunks an array into size large chunks. 
 * The last chunk may contain less than size elements. 
 * @param <T>
 * @param arr The array to work on 
 * @param size The size of each chunk 
 * @return a list of arrays
 */
public static <T> List<T[]> chunk(T[] arr, int size) {

    if (size <= 0)
        throw new IllegalArgumentException("Size must be > 0 : " + size);

    List<T[]> result = new ArrayList<T[]>();

    int from = 0;
    int to = size >= arr.length ? arr.length : size;

    while (from < arr.length) {
        T[] subArray = Arrays.copyOfRange(arr, from, to);
        from = to;
        to += size;
        if (to > arr.length) {
            to = arr.length;
        }
        result.add(subArray);
    }
    return result;
}

例如,创建大小为2的块:

String[] arr = {"a", "b", "c", "d", "e"} ;
List<String[]> chunks = chunk(arr,2);

这将返回三个数组:

{a,b}
{c,d}
{e}

Java仅支持数字数组,因此您仅适用于没有空格的数字数组。 如果您需要解决非数字值(例如Maps)的解决方案,请回发,我们将对其进行调查。

public void testMethod() {
    Object[] array={"one","two","three","four","five"};

    Object[][] chunkedArray = array_chunk(array,2);

    System.out.println(Arrays.deepToString(chunkedArray));


}

public Object[][] array_chunk(Object[] array,int size/*,FALSE Arrays are always numeric in java*/){
    Object[][] target= new Object[(array.length + size -1) / size][];

    for (int i = 0; i < target.length; i++) {
        int innerArraySize=array.length-i*size>=size?size:array.length-i*size;
        Object[] inner=new Object[innerArraySize];
        System.arraycopy(array, i*size, inner, 0, innerArraySize);
        target[i]=inner;
    }

    return target;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM