转换为特定类型的数组

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

“钥匙,名字”

我想把这一行转换成一个 String 数组,用逗号(,)分隔每个值,但是,我还想在返回最终数组之前修剪每个字段,所以我做了以下操作:

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

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

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

据我所知,问题在于 map 调用的返回类型,但是如何使它返回 String []数组呢?

70770 次浏览

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

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

This is actually a lambda expression for

.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

Parameters:

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

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

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