my string contains Integer
separated by space:
String number = "1 2 3 4 5 "
How I can get list of Integer
from this string ?
To print a list of integers similar to how you printed the strings in the previous example: Use the map() function to transform them into strings. Call join() method to merge them into one string. Print the resulting string out using the print() function.
You can use a Scanner
to read the string one integer at a time.
Scanner scanner = new Scanner(number);
List<Integer> list = new ArrayList<Integer>();
while (scanner.hasNextInt()) {
list.add(scanner.nextInt());
}
Using Java8 Stream API map and mapToInt
function you can archive this easily:
String number = "1 2 3 4 5";
List<Integer> x = Arrays.stream(number.split("\\s"))
.map(Integer::parseInt)
.collect(Collectors.toList());
or
String stringNum = "1 2 3 4 5 6 7 8 9 0";
List<Integer> poolList = Arrays.stream(stringNum.split("\\s"))
.mapToInt(Integer::parseInt)
.boxed()
.collect(Collectors.toList());
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