'Java Generics: 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?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source