Convert Comma Separated String To List Without Intermediate Container


Answer :

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.




Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable