Java 流 toArray() 转换为特定类型的数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40902315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:58:50  来源:igfitidea点击:

Java stream toArray() convert to a specific type of array

javaarraysjava-8java-stream

提问by arielnmz

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:

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

"Key, Name"

“钥匙,名字”

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

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[] 数组而不是 String[] 数组。经过进一步检查,我可以确认内容实际上是 String 实例,但数组本身是 Object 元素。让我来说明一下,这就是调试器对返回对象所说的:

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

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?

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

采纳答案by Mritunjay

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

使用toArray(size -> new String[size])toArray(String[]::new)

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

This is actually a lambda expression for

这实际上是一个 lambda 表达式

.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.

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

From the docs

文档

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

Type Parameters:

类型参数:

A - the element type of the resulting array

A - 结果数组的元素类型

Parameters:

参数:

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

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

回答by Paul Buis

String[]::newis a function that invokes the new"pseudo-method" for the String[]type just like String::trimis a function that invokes the real trimmethod of the String type. The value passed to the String::newfunction by toArray is the size of the collection on the right-hand side of the .toArray() method invocation.

String[]::new是一个调用类型的new“伪方法”的函数,String[]就像String::trim调用trimString 类型的真实方法的函数一样。String::newtoArray传递给函数的值是 .toArray() 方法调用右侧的集合的大小。

If you replaced String[]::newwith n->new String[n]you might be more comfortable with the syntax just like you could replace String::trimwith the less cool s->s.trim()

如果你替换String[]::newn->new String[n]你可能对语法更舒服,就像你可以String::trim用不那么酷的替换s->s.trim()