The easiest method is to use the toArray(IntFunction<A[]> generator)
method with an array constructor reference.
(最简单的方法是将toArray(IntFunction<A[]> generator)
方法与数组构造函数引用一起使用。)
This is suggested in the API documentation for the method . (在API文档中建议该方法 。)
String[] stringArray = stringStream.toArray(String[]::new);
What it does is find a method that takes in an integer (the size) as argument, and returns a String[]
, which is exactly what (one of the overloads of) new String[]
does.
(它的作用是找到一个以整数(大小)作为参数的方法,并返回String[]
,而这正是new String[]
(的重载之一)所做的事情。)
You could also write your own IntFunction
:
(您也可以编写自己的IntFunction
:)
Stream<String> stringStream = ...;
String[] stringArray = stringStream.toArray(size -> new String[size]);
The purpose of the IntFunction<A[]> generator
is to convert an integer, the size of the array, to a new array.
(IntFunction<A[]> generator
是将整数(数组的大小)转换为新数组。)
Example code:
(示例代码:)
Stream<String> stringStream = Stream.of("a", "b", "c");
String[] stringArray = stringStream.toArray(size -> new String[size]);
Arrays.stream(stringArray).forEach(System.out::println);
Prints:
(打印:)
a
b
c
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…