Reputation: 3717
So I have User class
User{
id
name
}
& I need to convert List<User>
to Array of using stream so one way I am doing is to convert into list and then to array
coll.stream().map(am -> am.getId())
.collect(Collectors.<Integer>toList())
.toArray(new Integer[0])
but I think there should be another approach to directly convert into array rather than adding in list and then convert into array.
Upvotes: 13
Views: 15163
Reputation: 56433
Unless there is a really good reason to collect into a Integer[]
you're probably looking for:
int[] ids = coll.stream()
.mapToInt(User::getId)
.toArray();
Upvotes: 6
Reputation: 6946
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 array from the stream rather than a list.
Upvotes: 17