Java 8 code example demonstrating the conversion of a list to an array

Use the following method in Java to convert a list to an array of reference types. Solution 2 can be used unless there is a specific reason to collect into a different type. This tutorial explores different methods for converting a list to an array in Java.


Solution 1:

Stream offers the possibility of utilizing
<A> A[] toArray(IntFunction<A[]> generator)
.

Integer[] ids = coll.stream()
    .map(am -> am.getId())
    .toArray(Integer[]::new)

This will generate an array from the stream instead of a list.


Solution 2:


If there isn’t a compelling justification to gather into a
Integer[]
, you’re likely seeking:

int[] ids = coll.stream()
                .mapToInt(User::getId)
                .toArray();

Frequently Asked Questions

Posted in Uncategorized