A new default method toArray(IntFunction) has been added to the java.util.Collection interface:
toArray(IntFunction)
java.util.Collection
default <T> T[] toArray(IntFunction<T[]> generator)
It returns a new array consisting of the elements of this collection. The provided generator function is used to allocate the returned array.
The new method is an overloaded of the existing toArray(....) methods.
toArray(....)
package com.logicbig.example; import java.util.Arrays; import java.util.List; public class CollectionToArrayExample { public static void main(String[] args) { List<String> list = List.of("apple", "banana", "orange"); //old methods String[] array = list.toArray(new String[list.size()]); System.out.println(Arrays.toString(array)); Object[] objects = list.toArray(); System.out.println(Arrays.toString(objects)); //new method String[] array2 = list.toArray(String[]::new); System.out.println(Arrays.toString(array2)); } }
[apple, banana, orange][apple, banana, orange][apple, banana, orange]
Dependencies and Technologies Used: