convert comma separated string to list without intermediate container

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());

I really like @MarounMaroun's answer but I wonder if it is even better to use the Arrays.stream-method instead of Arrays.asList.

int[] numbers = Arrays.stream(numbersArray.split(","))
                .map(String::trim).mapToInt(Integer::parseInt).toArray();

This SO-question discusses this further and summarizes it as such:

because you leave the conversion of the array to a stream to the JDK - let it be responsible for efficiency etc.


If you are willing to use Google Guava ( https://code.google.com/p/guava-libraries/ ) , splitter is your friend

    List<Integer> list = new ArrayList<Integer>();
    for ( String s : Splitter.on(',').trimResults().omitEmptyStrings().split("1, 2, 3, 14, 5,") ) {
      list.add(Integer.parseInt(s)); 
    }

or, you could use something similar to your original approach and:

List<Integer> list = new ArrayList<Integer>();
for (String s :"1, 2, 3, 5, 7, 9,".split(",") ) {
    list.add(Integer.parseInt(s.trim()));
}

Tags:

Java