Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

JDK 11: New Default Collection Method toArray(IntFunction) [Snippet]

DZone's Guide to

JDK 11: New Default Collection Method toArray(IntFunction) [Snippet]

Check out this post on how to use the new default Collection method toArray(IntFunction) in JDK 11. Click here to get the code now.

· Java Zone ·
Free Resource

Start coding something amazing with our library of open source Cloud code patterns. Content provided by IBM.

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 the desired runtime type." This new default methodCollection.toArray(IntFunction), works similarly to the same-named method already available on the Stream interface, Stream.toArray(IntFunction).

The next code listing demonstrates a 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, the order of the String in the generated array can be different than the order of the Stringspecified for initialization of the Set. This is demonstrated in the next screen snapshot. This also indicates that I'm using JDK 11 Early Access Build 23 for this example).

Image title

Many of us use the Java collections more frequently than arrays, but there are times when 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 that it is no longer possible to pass null to the Collection.toArray(-) method. During this, the compiler is unable to distinguish them and will report the error message "reference to toArrayis ambiguous." This is not much of a price to pay since both methods throw a NullPointerException anyway when null is passed to them.

Use this tool to look at the contents of GitHub and classify code based on the programming language used.  Content provided by IBM Developer.

Topics:
java ,code ,snippet ,collection methods ,nullpointerexception ,array ,string ,set ,jdk 11 ,intfunction

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}