rajadilipkolli
rajadilipkolli

Reputation: 3601

Convert List of one type to Array of another type using Java 8

I need to convert List of string to Array of userdefinedType and for array I need to convert string to long.

I have achieved the same using below approach to achieve it

TeamsNumberIdentifier[] securityPolicyIdArray = securityPolicyIds.stream()
                .map(securityPolicy -> new TeamsNumberIdentifier(Long.valueOf(securityPolicy)))
                .collect(Collectors.toCollection(ArrayList::new))
                .toArray(new TeamsNumberIdentifier[securityPolicyIds.size()]);

Is there any better approach to convert this?

Upvotes: 0

Views: 1058

Answers (2)

Nick Vanderhoven
Nick Vanderhoven

Reputation: 3093

I would write it like this:

securityPolicyIds.stream()
                 .map(Long::valueOf)
                 .map(TeamsNumberIdentifier::new)
                 .toArray(TeamsNumberIdentifier[]::new);

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691685

You don't need to create a temporary ArrayList. Just use toArray() on the stream:

TeamsNumberIdentifier[] securityPolicyIdArray = securityPolicyIds.stream()
            .map(securityPolicy -> new TeamsNumberIdentifier(Long.valueOf(securityPolicy)))
            .toArray(TeamsNumberIdentifier[]::new);

But in general, I would tend to avoid arrays in the first place, and use lists instead.

Upvotes: 7

Related Questions