Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to collect the results of a Stream in a primitive array?

I'm trying to convert 2D list to a 2D int array. However, it seems I can only collect objects, not primitives.

When I do:

data.stream().map(l -> l.stream().toArray(int[]::new)).toArray(int[][]::new);

I get the compile-time error Cannot infer type argument(s) for <R> map(Function<? super T,? extends R>).

However, if I change int[] to Integer[], it compiles. How can I get it to just use int?

like image 735
ack Avatar asked Jun 01 '17 01:06

ack


People also ask

Can you use streams with primitives Java?

Streams primarily work with collections of objects and not primitive types. Fortunately, to provide a way to work with the three most used primitive types – int, long and double – the standard library includes three primitive-specialized implementations: IntStream, LongStream, and DoubleStream.


1 Answers

Use mapToInt method to produce a stream of primitive integers:

int[][] res = data.stream().map(l -> l.stream().mapToInt(v -> v).toArray()).toArray(int[][]::new);

The inner toArray call no longer needs int[]::new, because IntStream produces int[].

Demo.

like image 105
Sergey Kalinichenko Avatar answered Oct 18 '22 03:10

Sergey Kalinichenko