Core Java

Java 11: Converting a Collection to an Array

In Java 11, a new default method, toArray(IntFunction), has been added to the java.util.Collection interface, which allows the collection’s elements to be transferred to a newly created array of a desired runtime type.

For example:

// Java 11
List<String> list = Arrays.asList("foo","bar","baz");
String[] array = list.toArray(String[]::new);

// The above is equivalent to:
String[] array2 = list.toArray(new String[0]);
Published on Java Code Geeks with permission by Fahd Shariff, partner at our JCG program. See the original article here: Java 11: Converting a Collection to an Array

Opinions expressed by Java Code Geeks contributors are their own.

Fahd Shariff

Fahd is a software engineer working in the financial services industry. He is passionate about technology and specializes in Java application development in distributed environments.
Subscribe
Notify of
guest

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

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
5 years ago

That’s cool. Good to know.

Back to top button