gpt4 book ai didi

java - 将 array_chunk 从 php 转换为 java

转载 作者:行者123 更新时间:2023-12-02 00:47:36 25 4
gpt4 key购买 nike

我的PHP代码是:

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

最佳答案

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

/**
* 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 的 block :

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

这将返回三个数组:

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

关于java - 将 array_chunk 从 php 转换为 java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4497972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com