Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert comma separated string to list without intermediate container

Tags:

java

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>

like image 914
user3127896 Avatar asked Sep 04 '25 17:09

user3127896


2 Answers

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.

like image 181
Maroun Avatar answered Sep 07 '25 08:09

Maroun


Using java 8 Streams:

List<Integer> longIds = Stream.of(commaSeperatedString.split(","))
                .map(Integer::parseInt)
                .collect(Collectors.toList());
like image 29
Mohsen Kashi Avatar answered Sep 07 '25 07:09

Mohsen Kashi