Search code examples
javagenericslambdajava-streamtoarray

Java Generics: Compilation failure when using Stream.toArray()


Given a simple generic class:

private static class Container<T> {
    private List<T> aList;
    private T aValue;

    private Container(List<T> aList, T aValue) {
        this.aList = aList;
        this.aValue = aValue;
    }
}

Initialize a list of that class:

List<Container<?>> container = new ArrayList<>();
// Add some elements...

Not possible (The method toArray(IntFunction<A[]>) in the type Stream<List<capture#1-of ?>> is not applicable for the arguments (List<?>[])):

container.stream().map(value -> value.aList).toArray(new List<?>[0]);

Possible:

container.stream().map(value -> value.aList).collect(Collectors.toList()).toArray(new List<?>[0]);

Why?


Solution

  • Stream's toArray takes a IntFunction<A[]> - i.e. a function that accepts an int and returns an array.

    You tried to pass an array to it.

    It should be used as follows:

    container.stream().map(value -> value.aList).toArray(List<?>[]::new)