Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert list<Object> to array of <Id> in java 8 stream

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.

like image 910
user1298426 Avatar asked Jan 10 '18 07:01

user1298426


2 Answers

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();
like image 142
Ousmane D. Avatar answered Nov 08 '22 03:11

Ousmane D.


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.

like image 34
ByeBye Avatar answered Nov 08 '22 03:11

ByeBye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!