How to convert a Java 8 Stream to an Array?(如何将 Java 8 流转换为数组?)
问题描述
What is the easiest/shortest way to convert a Java 8 Stream
into an array?
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.
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.
You could also write your own IntFunction
:
The purpose of the IntFunction<A[]> generator
is to convert an integer, the size of the array, to a new array.
Example code:
Prints:
这篇关于如何将 Java 8 流转换为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!