Java 11 - Convert Collection to Array

How do you turn a collection into an array? Here what I'll do to convert a list of String to an array in Java 8:

CollectionToArray.java
package com.dariawan.jdk8;

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

public class ListToArray {

    public static void main(String[] args) {
        List<String> list = Arrays.asList("Doc", "Grumpy", "Happy", 
                "Sleepy", "Dopey", "Bashful", "Sneezy");
        
        System.out.println("List to Array example in Java 8:");
        
        Object[] objects = list.toArray();
        System.out.println(Arrays.toString(objects));
        
        String[] array = list.toArray(new String[list.size()]);
        System.out.println(Arrays.toString(array));
    }
}
                    

With output:

List to Array example in Java 8: [Doc, Grumpy, Happy, Sleepy, Dopey, Bashful, Sneezy] [Doc, Grumpy, Happy, Sleepy, Dopey, Bashful, Sneezy]

list.toArray() convert the list into Object[] instead of String[], so normally I'll not do it. So it's left to second approach list.toArray(new String[list.size()]) which also not optimal (because computing the size of a collection can be "expensive"). Isn’t there a better way to do this?

In Java 11, a new default method toArray(IntFunction) has been added to the java.util.Collection interface:

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

Returns an array containing all of the elements in this collection, using the provided generator function to allocate the returned array.

API Note: This method acts as a bridge between array-based and collection-based APIs. It allows creation of an array of a particular runtime type. Use toArray() to create an array whose runtime type is Object[], or use toArray(T[]) to reuse an existing array.

Suppose x is a collection known to contain only strings. The following code can be used to dump the collection into a newly allocated array of String:

String[] y = x.toArray(String[]::new);

Let's take this new method in Java 11 example:

ListToArray.java
package com.dariawan.jdk11;

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

public class ListToArray {

    public static void main(String[] args) {
        List<String> list = List.of("Doc", "Grumpy", "Happy", 
                "Sleepy", "Dopey", "Bashful", "Sneezy");
        
        System.out.println("List to Array example in Java 11:");
        
        // old method
        String[] array1 = list.toArray(new String[list.size()]);
        System.out.println(Arrays.toString(array1));
        
        // new method
        String[] array2 = list.toArray(String[]::new);
        System.out.println(Arrays.toString(array2));
    }
}
                    

With output:

List to Array example in Java 11: [Doc, Grumpy, Happy, Sleepy, Dopey, Bashful, Sneezy] [Doc, Grumpy, Happy, Sleepy, Dopey, Bashful, Sneezy]

Here another example with HashSet/LinkedHashSet:

CollectionToArray.java
package com.dariawan.jdk11;

import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import lombok.ToString;

public class CollectionToArray {

    public static void main(String[] args) {
        List<Integer> list = List.of(1, 2, 3, 4, 5);
        
        Integer[] array1 = list.toArray(Integer[]::new);
        System.out.println(Arrays.toString(array1));
        
        Set<Integer> hset1 = new LinkedHashSet<>(list);
        hset1.remove(1);
        Integer[] array2 = hset1.toArray(Integer[]::new);
        System.out.println(Arrays.toString(array2));
        
        Set<Country> hset2 = new HashSet<>();
        hset2.add(new Country("ID", "Indonesia"));
        hset2.add(new Country("SG", "Singapore"));
        hset2.add(new Country("MY", "Malaysia"));
        Country[] array3 = hset2.toArray(Country[]::new);
        System.out.println(Arrays.toString(array3));
    }
    
    @ToString
    static class Country {
        String code;
        String name;
        
        Country(String code, String name) {
            this.code = code;
            this.name = name;
        }
    }
}
                    

The ouput is:

[1, 2, 3, 4, 5] [2, 3, 4, 5] [CollectionToArray.Country(code=ID, name=Indonesia), CollectionToArray.Country(code=SG, name=Singapore), CollectionToArray.Country(code=MY, name=Malaysia)]