uraza
uraza

Reputation: 957

String array to a collection of Integer?

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());

Upvotes: 6

Views: 902

Answers (3)

zhouxin
zhouxin

Reputation: 230

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. :)

Upvotes: 0

G&#225;bor Bakos
G&#225;bor Bakos

Reputation: 9100

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.

Upvotes: 3

Misha
Misha

Reputation: 28153

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());

Upvotes: 8

Related Questions