Tuesday, December 25, 2018

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]);

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.