Java Joy: Turn Streams Into Arrays [Snippet]
The Java Stream API has many useful methods. If we want to transform a Stream to a Java array we can use the toArray method. Without an argument the result i...
Join the DZone community and get the full member experience.Join For Free
Stream API has many useful methods. If we want to transform a
Stream into a Java array, we can use the
toArray method. Without an argument, the result is an object array (
Object), but we can also use an argument to return an array of another type. The easiest way is to use the contructor of the array type we want as a method reference. Then, the result is an array of the given type with the elements of the stream.
This is very useful if we have a Java
Stream and want to use the elements to invoke a method with a variable arguments parameter. In Java, we can pass an array object as variable arguments argument to a method. So if we transform the
Stream into an array we can invoke the method with that value.
In the following example, we see how we transform a
String values to a
String object. We use this
String object to invoke a method with a varargs parameter of type
Written with Java 15.0.1
Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.