String array to Integer collection?

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

 String[] myStringNumbers; Arrays.stream(Arrays.asList(myStringNumbers).stream().mapToInt(Integer::parseInt).toArray()).boxed().collect( Collectors.toList()); 
+6
source share
3 answers

You do not need to create an intermediate array. Just analyze and assemble (with the static import of Collectors.toList ):

 Arrays.stream(myStringNumbers).map(Integer::parseInt).collect(toList()); 
+8
source

There is no need to use parseInt , as it will put the result in the collection, and as @Misha said, you can use Arrays.stream to create the stream. Therefore, 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 numbers should not start with 0 , # or 0x unless you want surprises). If you need only basic 10 numbers, Integer::valueOf is the best choice.

+3
source

That's what I think:

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

Hope this helps. :)

0
source

All Articles