Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Given the array and chunkSize. I have to produce the desired output
array = [1,2,3,4,5]
chunkSize = 1
desired output [1] [2] [3] [4] [5]

What I have tried:

I have tried using IntStream
Java
public static List<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))
                .collect(Collectors.toList());//how to fix this line error on new
    }


The function call I am doing in main method as:
List<int[]> list = chunk(original, splitSize);
list.forEach(splitArray -> System.out.println(Arrays.toString(splitArray)));
Posted
Updated 11-Dec-22 17:33pm

1 solution

There could be multiple ways to do it. If there is no issue of space, I would prefer Arrays.copyOfRange()

In it, the copyOfRange() creates a new array of the same type as the original array, and contains the items of the specified range of the original array into a new array.

Syntax:
Java
public static T[] copyOfRange(T[] original, int from, int to)

// original – the array from which a range is to be copied
// from – the initial index of the range to be copied, inclusive
// to – the final index of the range to be copied, exclusive

More details: Java.util.Arrays.copyOfRange() Method[^]

Example usage:
Java
int[] arr1 = new int[] {15, 10, 45, 55};
int chunk = 2; // provided as input
for(int i=0; i<arr1.length; i+=chunk){
    System.out.println(Arrays.toString(Arrays.copyOfRange(arr1, i, Math.min(arr1.length,i+chunk))));
}
 
Share this answer
 
Comments
Vibhanshu 2022 12-Dec-22 4:21am    
I have restriction of the return type it should be of the form List<int[]>
Sandeep Mewara 12-Dec-22 5:17am    
Wouldn't they be able to fill the chunked data there as needed format?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900