Java11 enhanced toArray() method to support with Argument IntFunction.

toArray is an default method added to java.util.collection interface.

It used an easy way to convert Collections to Array with a simplified process.

Let’s see how to convert the collection to the array before java11.

We have two options as given below to convert to array.

    Object[] toArray();
    <T> T[] toArray(T[] a);

One way is using toArray(), which returns Object Array, Another way using call toArray using create an empty string with the size of a collection. Here is an example in the java10 version

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class java11toArray {
    public static void main(String[] args) {
        List<String> numbers = new ArrayList<>();
        numbers.add("one");
        numbers.add("two");
        numbers.add("three");
        // Before java 11 version
        Object[] objArray = numbers.toArray();
        System.out.println(Arrays.toString(objArray));

        String[] numbersArray = numbers.toArray(new String[numbers.size()]);
        System.out.println(numbersArray);

    }
}

Java11 simplified with toArray default method.

    default <T> T[] toArray(IntFunction<T[]> generator) {

Here is a java11 toArray example to convert the collection into Array of String

import java.util.ArrayList;
import java.util.List;

public class java11toArray {
    public static void main(String[] args) {
        List<String> numbers = new ArrayList<>();
        numbers.add("one");
        numbers.add("two");
        numbers.add("three");
        String[] numbersArray = numbers.toArray(String[]::new);
    }
}