Site icon Automation Dojos

Convert List to Array Using Stream with Param

There is an overloaded version of the Stream.toArray method which can be used to return a result array that is of the same data type as the input array. The following code demonstrates this:

Firstly, the ‘stream()‘ method is invoked on the input List which returns a Stream corresponding to the List. Then the overloaded ‘toArray‘ method is invoked.

This method accepts an IntFunction interface as a parameter. IntFunction is an in-built functional interface that accepts an input of integer data type and returns a result of any data type.

Here, it is implemented via a lambda expression that accepts as input the length of the array and returns an Integer array of the specified length. So this is then used by the ‘Stream.toArray‘ method to create the output array.

This code prints the following output:

2 4 6 8 10
Exit mobile version