Convert List to Array Using Stream without Param

Java 8 has added the Stream API that helps to easily perform bulk operations on Collections. A new method called stream() has been added to all the collection interfaces that returns a Stream corresponding to the underlying collection.

There is a toArray method available on the Stream interface that can be used to convert the Stream to an array. So this method can be used to convert a List to an array. There are two overloaded versions of this method as explained below.

This Stream.toArray method does not accept any input parameter and it returns an object array. The following code demonstrates this approach:

Here, firstly the stream() method is invoked on the input List. This returns a Stream corresponding to the List. Then the toArray method is invoked on the Stream. This returns an object array.

Hence 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

Concatenate Strings Using StringBuilder.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...

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...

Rounding Decimal Number With Java DecimalFormat

The DecimalFormat class has a method called setRoundingMode() which can be used for setting the rounding mode for DecimalFormat object. The setRoundingMode() accepts RoundingMode...

Â

MORE IN THIS CATEGORY

Remove Duplicates from List Using Set.addAll

The Set interface has a method called addAll. This accepts a 'Collection' as the parameter. So if you invoke this method by passing the...

Convert String to java.time.LocalDate with Formatter

The LocalDate class has an overloaded parse() method. In addition to the String Date, it accepts a DateTimeFormatter instance that specifies the format of...

How To Sort List in Java

Introduction A List is an interface in the Java collection framework. It can be used to store objects. Programmers often encounter scenarios where they need...

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