Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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<?>[])):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading