也许这很简单,但我实际上是 Java 8 特性的菜鸟,不知道如何实现。我有一个包含以下文本的简单行:
"Key, Name"
我想将该行转换为字符串数组,用逗号 (,) 分隔每个值,但是,我还想在返回最终数组之前修剪每个字段,所以我做了以下操作:
Arrays.stream(line.split(",")).map(String::trim).toArray();
但是,这会返回 Object[] 数组而不是 String[] 数组。经过进一步检查,我可以确认内容实际上是 String 实例,但数组本身是 Object 元素。让我来说明这一点,这就是调试器对返回的对象所说的:
Object[]:
0 = (String) "Key"
1 = (String) "Name"
据我所知,问题出在 map 调用的返回类型上,但是我怎样才能让它返回一个 String[] 数组呢?
最佳答案
使用 toArray(size -> new String[size])
或 toArray(String[]::new)
。
String[] strings = Arrays.stream(line.split(",")).map(String::trim).toArray(String[]::new);
这实际上是
的 lambda 表达式.toArray(new IntFunction<String[]>() {
@Override
public String[] apply(int size) {
return new String[size];
}
});
您在哪里告诉将数组转换为相同大小的字符串数组。
来自 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);
类型参数:
A - the element type of the resulting array
参数:
generator - a function which produces a new array of the desired type and the provided length
关于Java 流 toArray() 转换为特定类型的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40902315/