如何在原始数组中收集Stream的结果? [英] How to collect the results of a Stream in a primitive array?

查看:93
本文介绍了如何在原始数组中收集Stream的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将2D列表转换为2D int数组.但是,看来我只能收集对象,而不能收集基元.

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

当我这样做时:

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

我收到编译时错误Cannot infer type argument(s) for <R> map(Function<? super T,? extends R>).

但是,如果将int[]更改为Integer[],它将编译.我怎样才能只使用int?

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

推荐答案

使用

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);

内部toArray调用不再需要int[]::new,因为IntStream生成int[].

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

演示.

这篇关于如何在原始数组中收集Stream的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆