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());
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());
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With