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
Tushar Sharma
Tushar Sharmahttps://www.automationdojos.com
Hi! This is Tushar, the author of 'Automation Dojos'. A passionate IT professional with a big appetite for learning, I enjoy technical content creation and curation. Hope you are having a good time! Don't forget to subscribe and stay in touch. Wishing you happy learning!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Recent Posts

RELATED POSTS

Format Decimal Numbers using Strings Within Pattern

As mentioned in earlier posts, the java.text.DecimalFormat class is used to format decimal numbers via predefined patterns specified as String. Apart from the decimal separator,...

How To Customize GitBash For Windows

By default the GitBash prompt settings / configuration come from shell script called 'git-prompt.sh'. This is usually hosted inside 'profile.d' directory inside the GitBash...

Convert List to Array Using ToArray With Param

There is an overloaded version of the toArray method. This accepts an array as a parameter and returns a result array that is of the same...

Â

MORE IN THIS CATEGORY

Concatenate Strings Using StringBuffer.append()

In addition to String, Java has the java.lang.StringBuffer and java.lang.StringBuilder classes. These can also be used to concatenate Strings. The advantage of these...

Getting Started With Hibernate

Introduction Hibernate is a framework which allows you to access database tables from Java code. Before Hibernate came into existence, JDBC was widely used. JDBC...

Introduction to Apache Maven

1. What is Maven When you write a software application, there are many steps in it like adding the necessary JAR files, compiling the source...

RECENT 'HOW-TO'

How To Install Oh-My-Posh On Windows PowerShell

Oh-My-Posh is a powerful custom prompt engine for any shell that has the ability to adjust the prompt string with a function or variable. It does not...

SIMILAR ON CODEX

- Advertisement -spot_img