将array_chunk从php转换为java

时间:2010-12-21 09:51:39

标签: java php

我的PHP代码是:

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

2 个答案:

答案 0 :(得分:3)

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}

答案 1 :(得分:0)

Java仅支持数值数组,因此您只能使用没有间隙的数字数组。如果你需要一个处理非数字值(即地图)的解决方案,我会调查它。

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