0

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?

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I too does the same but my API needs arrays instead of lists
1

I would write it like this:

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

1 Comment

This is more efficient one and more clean , I will use the same

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.