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
Post a Comment