Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
like image 333
uraza Avatar asked Apr 15 '16 07:04

uraza


2 Answers

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());
like image 100
Misha Avatar answered Oct 12 '22 22:10

Misha


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.

like image 34
Gábor Bakos Avatar answered Oct 12 '22 23:10

Gábor Bakos