I need to convert comma separated string to list of integers. For example if I have following string
String numbersArray = "1, 2, 3, 5, 7, 9,";
Is there a way how to convert it at once to List<Integer>
?
Now i see only one way to do it.
List<String> numbers = Arrays.asList(numbersArray.split(","));
And then
List<Integer> numbersInt = new ArrayList<>();
for (String number : numbers) {
numbersInt.add(Integer.valueOf(nubmer));
}
I'm curious is there a way how to miss part with List<String>
and at the first onset convert it to List<Integer>
If you're using Java 8, you can:
int[] numbers = Arrays.asList(numbersArray.split(",")).stream()
.map(String::trim)
.mapToInt(Integer::parseInt).toArray();
If not, I think your approach is the best option available.
Using java 8 Streams:
List<Integer> longIds = Stream.of(commaSeperatedString.split(","))
.map(Integer::parseInt)
.collect(Collectors.toList());
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