22

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?

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
ack
  • 1,181
  • 1
  • 17
  • 36
  • 2
    For the lambda, try `l.stream().mapToInt(Integer::intValue).toArray()` – 4castle Jun 01 '17 at 01:51
  • How can I collect the results of this though? That just performs operations on the Stream without storing the results. – ack Jun 01 '17 at 01:53
  • 2
    My suggestion handles the incorrect lambda you were using. It will collect properly now. – 4castle Jun 01 '17 at 01:55

1 Answers1

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523