Reputation: 3601
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
Reputation: 3093
I would write it like this:
securityPolicyIds.stream()
.map(Long::valueOf)
.map(TeamsNumberIdentifier::new)
.toArray(TeamsNumberIdentifier[]::new);
Upvotes: 1
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