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.
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With