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?
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.
Regular expression splitting is what you're looking for
Stream.of(ints.split(", "))
.map(Integer::parseInt)
.collect(Collectors.toList());
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With