如何将 Java 8 Stream 转换为数组? [英] How to convert a Java 8 Stream to an Array?
问题描述
将 Java 8 Stream
转换为数组的最简单/最短的方法是什么?
What is the easiest/shortest way to convert a Java 8 Stream
into an array?
推荐答案
最简单的方法是使用带有数组构造函数引用的 toArray(IntFunction generator)
方法.这在 该方法的 API 文档.
The easiest method is to use the toArray(IntFunction<A[]> generator)
method with an array constructor reference. This is suggested in the API documentation for the method.
String[] stringArray = stringStream.toArray(String[]::new);
它所做的是找到一个以整数(大小)作为参数的方法,并返回一个String[]
,这正是的(重载之一)new String[]
确实如此.
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.
您也可以编写自己的IntFunction
:
Stream<String> stringStream = ...;
String[] stringArray = stringStream.toArray(size -> new String[size]);
IntFunction的目的generator
是将一个整数,即数组的大小,转换为一个新的数组.
The purpose of the IntFunction<A[]> generator
is to convert an integer, the size of the array, to a new array.
示例代码:
Stream<String> stringStream = Stream.of("a", "b", "c");
String[] stringArray = stringStream.toArray(size -> new String[size]);
Arrays.stream(stringArray).forEach(System.out::println);
打印:
a
b
c
这篇关于如何将 Java 8 Stream 转换为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!