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

1

24

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?

Ineluctable answered 1/6, 2017 at 1:42 Comment(3)
For the lambda, try l.stream().mapToInt(Integer::intValue).toArray()Pothouse
How can I collect the results of this though? That just performs operations on the Stream without storing the results.Ineluctable
My suggestion handles the incorrect lambda you were using. It will collect properly now.Pothouse
O
33

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.

Oxidation answered 1/6, 2017 at 1:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.