Java 流 toArray() 转换为特定类型的数组 [英] Java stream toArray() convert to a specific type of array

查看:43
本文介绍了Java 流 toArray() 转换为特定类型的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许这很简单,但我实际上是 Java 8 特性的菜鸟,不知道如何实现这一点.我有一个包含以下文本的简单行:

Maybe this is very simple but I'm actually a noob on Java 8 features and don't know how to accomplish this. I have this simple line that contains the following text:

密钥,名称"

并且我想将该行转换为字符串数组,用逗号 (,) 分隔每个值,但是,我还想在返回最终数组之前修剪每个字段,因此我执行了以下操作:

and I want to convert that line into a String array, separating each value by the comma (,), however, I also want to trim every field before returning the final array, so I did the following:

Arrays.stream(line.split(",")).map(String::trim).toArray();

然而,这将返回一个 Object[] 数组而不是一个 String[] 数组.经过进一步检查,我可以确认内容实际上是 String 实例,但数组本身是 Object 元素.让我来说明一下,这就是调试器对返回的对象所说的:

However, this returns an Object[] array rather than a String[] array. Upon further inspection, I can confirm that the contents are actually String instances, but the array itself is of Object elements. Let me illustrate this, this is what the debugger says of the returned object:

Object[]:
    0 = (String) "Key"
    1 = (String) "Name"

据我所知,问题出在 map 调用的返回类型上,但如何让它返回一个 String[] 数组?

As far as I can tell, the problem is in the return type of the map call, but how can I make it return a String[] array?

推荐答案

Use toArray(size -> new String[size]) or toArray(String[]::new).

String[] strings = Arrays.stream(line.split(",")).map(String::trim).toArray(String[]::new);

这实际上是

.toArray(new IntFunction<String[]>() {
        @Override
        public String[] apply(int size) {
            return new String[size];
        }
    });

您在哪里告诉将数组转换为相同大小的字符串数组.

Where you are telling convert the array to a String array of same size.

来自 文档

生成器函数接受一个整数,它是所需数组的大小,并生成一个所需大小的数组.这可以用数组构造函数引用来简洁地表达:

The generator function takes an integer, which is the size of the desired array, and produces an array of the desired size. This can be concisely expressed with an array constructor reference:

 Person[] men = people.stream()
                      .filter(p -> p.getGender() == MALE)
                      .toArray(Person[]::new);

类型参数:

A - 结果数组的元素类型

A - the element type of the resulting array

参数:

generator - 生成所需类型和提供长度的新数组的函数

generator - a function which produces a new array of the desired type and the provided length

这篇关于Java 流 toArray() 转换为特定类型的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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