user1298426
user1298426

Reputation: 3717

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.

Upvotes: 13

Views: 15163

Answers (2)

Ousmane D.
Ousmane D.

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

ByeBye
ByeBye

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

Related Questions