如何在Java中将字符串数组分成小的块数组?

35
以下是需要帮助的代码片段示例:
示例:
[1,2,3,4,5]
  • 如果块大小为1,则为[1,2,3,4,5]
  • 如果块大小为2,则为[1,2][3,4][5]
  • 如果块大小为3,则为[1,2,3][4,5]
  • 如果块大小为4,则为[1,2,3,4][5]

Java(来自注释):

int counter = 0;
for (int i=0; i<array.length; i++) {
  if (count == chunksize) {
    //do something and initialize
    counter = 0;
  }
  counter++; 
}

20
如果块大小为1,为什么结果不是[1]和[2]和[3]和[4]和[5]? - Florent Bayle
1
你尝试过什么吗?如果你已经尝试过了,能否分享一下你的尝试经验? - SMA
你可以忽略第一部分,我只是举了一个例子。我们可以检查大小和块是否相等。当情况相同时,我们根本不需要块。 - user2323036
5
好的,我们可以忽略它,或者你可以提供正确的例子... - Tom
int counter = 0; for(int i=0; i<array.length; i++) { if(count == chunksize) { //做一些事情并且初始化counter = 0; } counter++; } - user2323036
17个回答

36

你可以使用 Arrays.copyOfRange(int[] original, int from, int to) 函数。

代码可能类似于:

int chunk = 2; // chunk size to divide
for(int i=0;i<original.length;i+=chunk){
    System.out.println(Arrays.toString(Arrays.copyOfRange(original, i, Math.min(original.length,i+chunk))));
}          

所以对于随机块需要再加一个循环吗? - Prashant
1
什么是随机块? - Reza
随机块意味着如果我想要所有块值...(1,2,3,4)。 - Prashant
是的,只需要用一个for循环来替换chunk=2部分。 - Reza
我喜欢这种方式。谢谢。 - Memin

29

在遇到同样的问题后,我偶然发现了这篇文章。这是我解决它的方法(我使用了Arrays.copyOfRange()):

public static int[][] splitArray(int[] arrayToSplit, int chunkSize){
    if(chunkSize<=0){
        return null;  // just in case :)
    }
    // first we have to check if the array can be split in multiple 
    // arrays of equal 'chunk' size
    int rest = arrayToSplit.length % chunkSize;  // if rest>0 then our last array will have less elements than the others 
    // then we check in how many arrays we can split our input array
    int chunks = arrayToSplit.length / chunkSize + (rest > 0 ? 1 : 0); // we may have to add an additional array for the 'rest'
    // now we know how many arrays we need and create our result array
    int[][] arrays = new int[chunks][];
    // we create our resulting arrays by copying the corresponding 
    // part from the input array. If we have a rest (rest>0), then
    // the last array will have less elements than the others. This 
    // needs to be handled separately, so we iterate 1 times less.
    for(int i = 0; i < (rest > 0 ? chunks - 1 : chunks); i++){
        // this copies 'chunk' times 'chunkSize' elements into a new array
        arrays[i] = Arrays.copyOfRange(arrayToSplit, i * chunkSize, i * chunkSize + chunkSize);
    }
    if(rest > 0){ // only when we have a rest
        // we copy the remaining elements into the last chunk
        arrays[chunks - 1] = Arrays.copyOfRange(arrayToSplit, (chunks - 1) * chunkSize, (chunks - 1) * chunkSize + rest);
    }
    return arrays; // that's it
}

结果如下:

chunkSize = 1
[1]
[2]
[3]
[4]
[5]

chunkSize = 2
[1, 2]
[3, 4]
[5]

chunkSize = 3
[1, 2, 3]
[4, 5]

chunkSize = 4
[1, 2, 3, 4]
[5]

chunkSize = 5
[1, 2, 3, 4, 5]

chunkSize = 6
[1, 2, 3, 4, 5]

4
实施得力。实际上对手头的问题给出了完整且正确的答案。 - Jaspreet

11

3
还有一个Apache Commons Collections ListUtils.partition() 方法。 - Tim

5

使用纯Java 8:

public class Chunk {
    public static void main(String[] args) {
        int[] input = {1,2,3,4,78,999,-1,456};
        int chunkSize = 3;

        int[][] chunked = chunk(input, chunkSize);

        Arrays.stream(chunked)
                .map(Arrays::toString)
                    .forEach(System.out::println);
    }

    public static int[][] chunk(int[] input, int chunkSize) {
        return IntStream.iterate(0, i -> i + chunkSize)
                .limit((long) Math.ceil((double) input.length / chunkSize))
                .mapToObj(j -> Arrays.copyOfRange(input, j, j + chunkSize > input.length ? input.length : j + chunkSize))
                .toArray(int[][]::new);
    }
}

[1, 2, 3]
[4, 78, 999]
[-1, 456]

j + chunkSize > input.length ? input.length : j + chunkSize can be replaced with Math.min(j + chunkSize, input.length) - Horațiu Udrea

4
        import java.util.Arrays;

        public class ArrayChunk {

            public static void main(String[] args) {

                int[] array = {1,2,3,4,5};

                
                 int[][] chunks1 = ArrayChunk(array, 1);
                 print(chunks1);
                 int[][] chunks2 = ArrayChunk(array, 2);
                 print(chunks2);
                 int[][] chunks3 = ArrayChunk(array, 3);
                 print(chunks3);

                 
                 
            }

            public static int[][] ArrayChunk(int[] array, int chunkSize) {
                int numOfChunks = (int) Math.ceil((double) array.length / chunkSize);
                int[][] output = new int[numOfChunks][];

                for (int i = 0; i < numOfChunks; i++) {
                    int start = i * chunkSize;
                    int length = Math.min(array.length - start, chunkSize);

                    int[] temp = new int[length];
                    System.arraycopy(array, start, temp, 0, length);
                    output[i] = temp;
                }

                //
                return output;
            }

            private static void print(int[][] output) {
                //
                System.out.println("======================");
                for (int[] x : output)
                    System.out.println(Arrays.toString(x));
            }
            

        }



        ======================
        [1]
        [2]
        [3]
        [4]
        [5]
        ======================
        [1, 2]
        [3, 4]
        [5]
        ======================
        [1, 2, 3]
        [4, 5]

2

试试这个:

迭代它并检查以确定块大小。

int chunkSize = userInput;

// 迭代并检查条件

char[] resultArray = Arrays.copyOfRange(inputArray, start, end);
start = start + end;  // check whether the start will exceeds the length of the array

1
public static int[][] chunkArray(int[] array, int chunkSize) {
        // first we need to get number of chunks by dividing length by chunkSize.
        int numOfChunks = (int)Math.ceil((double)array.length / chunkSize);
// we declare 2d array to save in the chunks
        int[][] output = new int[numOfChunks][];

        for(int i = 0; i < numOfChunks; i++) {
            int start = i * chunkSize;
            int length = Math.min(array.length - start, chunkSize);

            int[] temp = new int[length];
            System.arraycopy(array, start, temp, 0, length);
            output[i] = temp;
        }

        return output;
    }

1
   for(int i=0;i<list.size();){
    ArrayList<Integer>row = new ArrayList<Integer>();
    int k=0;
    while(k < chunksize){
        chunk.add(list.get(i));
        i++;
        k++;
    }
    System.out.println(chunk);
    nestedlist.add(chunk);
}   

其中list是一个一维数组,chunk是一个大小为chunksize的嵌套数组。


你的解决方案在某些情况下不起作用。如果 list.size() 为1且 chunksize 为3,该怎么办? - rakesh

0

这应该能解决问题

public static List<String> split(String string, int chunk) {
    Pattern pattern = Pattern.compile("(([0-9]+,){" + (chunk - 1)
            + "}[0-9]+)|[0-9]+");
    Matcher matcher = pattern.matcher(string);

    List<String> result = new ArrayList<String>();
    while (matcher.find())
        result.add("[" + matcher.group() + "]");

    return result;
}

测试代码:

for (int chunkSize = 1; chunkSize < 6; ++chunkSize) {
    System.out.println("test for chunk size: " + chunkSize);
    for (String string : split("[1,2,3,4,5]", chunkSize))
        System.out.format("\t%s\n", string);
}

输出:

test for chunk size: 1
    [1]
    [2]
    [3]
    [4]
    [5]
test for chunk size: 2
    [1,2]
    [3,4]
    [5]
test for chunk size: 3
    [1,2,3]
    [4]
    [5]
test for chunk size: 4
    [1,2,3,4]
    [5]
test for chunk size: 5
    [1,2,3,4,5]

0

问题:如何将数组按指定大小分成块? 答案: public class SplitArray {

public static void main(String[] args) {
        int[] original = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        int splitSize = 3;
        
        /* expected Output 
        [0, 1, 2]
        [3, 4, 5]
        [6, 7, 8]
        [9]
        */
    
        List<int[]> list = splitArray(original, splitSize);
        list.forEach(splitArray -> System.out.println(Arrays.toString(splitArray)));

}
public static List<int[]> splitArray(int[] array, int splitSize) {
    List<int[]> result = new ArrayList<>();
    int len=array.length;
    int arr[] = null;
    int size = splitSize;
    int k=0;
    for(int i=0;i<array.length;i++) {
        if(k==0)
        arr=new int[size];
        arr[k]=array[i];
        k++;
        if(k>size-1) {
            k=0;
            result.add(arr);
            len=len-size;
            if(len<splitSize) {
                size=len;
            }
        }
    }
    return result;
}

}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接