Reputation: 866
I have a String:
String ints = "1, 2, 3";
I would like to convert it to a list of ints:
List<Integer> intList
I am able to convert it to a list of strings this way:
List<String> list = Stream.of("1, 2, 3").collect(Collectors.toList());
But not to list of ints.
Any ideas?
Upvotes: 16
Views: 29728
Reputation: 137064
You need to split the string and make a Stream out of each parts. The method splitAsStream(input)
does exactly that:
Pattern pattern = Pattern.compile(", ");
List<Integer> list = pattern.splitAsStream(ints)
.map(Integer::valueOf)
.collect(Collectors.toList());
It returns a Stream<String>
of the part of the input string, that you can later map to an Integer
and collect into a list.
Note that you may want to store the pattern in a constant, and reuse it each time it is needed.
Upvotes: 28
Reputation: 125
You can just use the Array function asList, and then convert it the java8 way.
Don't forget to remove the white spaces.
List<Integer> erg = Arrays.asList(ints.replace(" ", "").split(",")).stream().map(Integer::parseInt).collect(Collectors.toList());
EDIT: Sorry i didn't see that it was a single string, thought it was a array of String.
Upvotes: 2
Reputation: 82899
First, split the string into individual numbers, then convert those (still string) to actual integers, and finally collect them in a list. You can do all of this by chaining stream operations.
String ints = "1, 2, 3";
List<Integer> intList = Stream
.of(ints.split(", "))
.map(Integer::valueOf)
.collect(Collectors.toList());
System.out.println(intList); // [1, 2, 3]
Upvotes: 3
Reputation: 220797
Regular expression splitting is what you're looking for
Stream.of(ints.split(", "))
.map(Integer::parseInt)
.collect(Collectors.toList());
Upvotes: 24