6

What is an easy way to convert a String[] to a Collection<Integer>? This is how I'm doing it right now but not sure if it's good:

String[] myStringNumbers;

Arrays.stream(Arrays.asList(myStringNumbers).stream().mapToInt(Integer::parseInt).toArray()).boxed().collect(
                    Collectors.toList());
0

3 Answers 3

8

You don't need to make an intermediate array. Just parse and collect (with static import of Collectors.toList):

Arrays.stream(myStringNumbers).map(Integer::parseInt).collect(toList());
Sign up to request clarification or add additional context in comments.

Comments

3

It is unnecessary to use parseInt as it will box the result to the collection, and as @Misha stated you can use Arrays.stream to create the stream. So you can use the following:

Arrays.stream(myStringNumbers).map(Integer::decode).collect(Collectors.toList());

Please note that this does not do any error handling (and the numbers should not start with 0, # or 0x in case you do not want surprises). If you want just base 10 numbers, Integer::valueOf is a better choice.

1 Comment

The int values are boxed in either case, so whether you use valueOf or parseInt makes no difference. And it’s quite strange to recommend the use of a different method like decode followed by a warning about the surprises caused by the fact that this method has a different purpose.
0

Here is what I think:

String[] myStringNumbers = {"1", "2"};
List<Integer> list = Stream.of(myStringNumbers).map(Integer::valueOf).collect(Collectors.toList());

I hope it can be some help. :)

Comments

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.