Convert <Objct> list to <Id> array in java 8 thread

So I have a user class

User{
id
name
}

& I need to convert List<User>to Array using a stream, so one of the ways I do is convert to a list and then to an array

coll.stream().map(am -> am.getId())
             .collect(Collectors.<Integer>toList())
             .toArray(new Integer[0])

but I think there should be a different approach to direct conversion to an array, rather than adding to a list and then converting to an array.

+4
source share
2 answers

You can use <A> A[] toArray(IntFunction<A[]> generator)from Stream:

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

which will create an array from a stream, not a list.

+4
source

If you have a really good reason to collect at Integer[], you're probably looking for:

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

Source: https://habr.com/ru/post/1691962/


All Articles