How to split a string array into small chunk arrays in java?

前端 未结 12 1935
春和景丽
春和景丽 2020-12-05 05:15

Below is the example of the code snippet which needs the help

Example:

[1,2,3,4,5]
  • if the chunk size is 1,
12条回答
  •  攒了一身酷
    2020-12-05 05:26

    Using pure 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]
    

提交回复
热议问题