Core Java

JDK 11: New Default Collection Method toArray(IntFunction)

The “JDK 11 Early-Access Release Notes” indicate that Early Access Build 20 of JDK 11 includes a new default method on the Collection interface that “allows the collection’s elements to be transferred to a newly created array of a desired runtime type”. This new default method [Collection.toArray(IntFunction)] works similarly to the same-named method already available on the Stream interface [Stream.toArray​(IntFunction)].

The next code listing demonstrates this new JDK 11 default Collection method in action (on a Set in this case).

final Set<String> names = Set.of("Fred", "Wilma", "Barney", "Betty");
out.println(Arrays.toString(names.toArray(String[]::new)));

Because I used an (unordered) Set, order of the Strings in the generated array can be different than the order the Strings were specified for initialization of the Set. This is demonstrated in the next screen snapshot (which also indicates that I’m using JDK 11 Early Access Build 23 for this example).

Default Method

Many of us use Java collections more frequently than arrays, but there are times we need to convert these collections to arrays. The default method Collection.toArray(IntFunction) provides a highly convenient mechanism for this. There was already a similar method on Collecton [Collection.toArray(T[])] and the existence of these two methods means it’s no longer possible to pass null to either Collection.toArray(-) method (compiler is unable to distinguish them and will report the error message “reference to toArray is ambiguous”). This is not much of a price to pay as both methods throw NullPointerException anyway when null is passed to them.

Published on Java Code Geeks with permission by Dustin Marx, partner at our JCG program. See the original article here: JDK 11: New Default Collection Method toArray(IntFunction)

Opinions expressed by Java Code Geeks contributors are their own.

Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button