Vibhanshu Jha
Vibhanshu Jha

Reputation: 1

Trying to solve a problem using stream API to find the chunk size. Giving error at .collect(Collectors.toList(ArrayList<int[]>::new)). Java 8+ Stream

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(ArrayList<int[]>::new));
}

I was trying to print array using Java 8 stream and it should return the type List<int[]> to the main function. example input are mentioned in the code.

Upvotes: -1

Views: 114

Answers (1)

ItsMoi
ItsMoi

Reputation: 21

The code is trying to create a List<int[]>, but the syntax used to create the list is incorrect. To fix this, you can replace the following line:

.collect(Collectors.toList(ArrayList<int[]>::new));

with this line:

.collect(Collectors.toList());

This will create a List<int[]> using the default List implementation, which is ArrayList.

Alternatively, you could specify the ArrayList implementation explicitly, like this:

.collect(Collectors.toCollection(ArrayList::new));

This will also create a List<int[]> using the ArrayList implementation.

Upvotes: 1

Related Questions