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

白昼怎懂夜的黑 提交于 2020-05-11 04:47:41

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/44297189/how-to-collect-the-results-of-a-stream-in-a-primitive-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!