convert array_chunk from php to java
my php code 开发者_StackOverflow社区is:
$splitArray = array_chunk($theArray,ceil(count($theArray) / 2),true);
php's array_chunk
function splits an array into chunks of the size you specify. You can do this in Java, by using Arrays.copyOfRange
and passing in the start and end points. Here is some sample code:
/**
* 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;
}
For example, to create chunks of size two:
String[] arr = {"a", "b", "c", "d", "e"} ;
List<String[]> chunks = chunk(arr,2);
Which will return three arrays:
{a,b}
{c,d}
{e}
Java only supports numeric arrays, so you this will only work for a numeric array which has no gaps. If u need a solution to deal with non-numeric values (i.e. Maps) post back, and I'll look into it.
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;
}
精彩评论