下面是我的代码:
Random rand = new Random();
String[] randomstrs = new String[3];
randomstrs = Arrays.stream(randomstrs)
.map(e -> Arrays.toString(rand.ints(3, 0, 5).toArray()).replaceAll("\\[|\\]", ""))
.collect(Collectors.toList())
.toArray(String[0]::new); // compile error
System.out.println(Arrays.toString(randomstrs));
我想知道如何在 .toArray(String[0]::new);
行使用方法引用。我知道我们可以做 new String[0]
但我对使用方法引用更感兴趣。有什么指点吗?
最佳答案
您可以删除 collect()
并从 Stream
生成一个数组直接:
randomstrs =
Arrays.stream(randomstrs)
.map(e -> Arrays.toString(rand.ints(3, 0, 5).toArray()).replaceAll("\\[|\\]", ""))
.toArray(String[]::new);
请注意Stream::toArray
预计 IntFunction<A[]>
,这意味着具有接受 int
的方法的功能接口(interface)参数并返回相关类型的数组。当您传递方法引用(例如 String[]::new
)时,您不会传递该方法的参数(在本例中是数组的长度)。
或者,如果您想收集Stream
到 List
然后将其转换为数组,您应该将数组实例传递给该方法,而不是函数式接口(interface)。因此你需要写:
randomstrs =
Arrays.stream(randomstrs)
.map(e -> Arrays.toString(rand.ints(3, 0, 5).toArray()).replaceAll("\\[|\\]", ""))
.collect (Collectors.toList())
.toArray(new String[0]);
关于java - 数组 Object[]::new 的方法引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49755051/