Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get list of Integer from String

Tags:

java

my string contains Integer separated by space:

String number = "1 2 3 4 5 "

How I can get list of Integer from this string ?

like image 804
hudi Avatar asked Jun 13 '12 07:06

hudi


People also ask

How do I print a list of integers from a string in Python?

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.


2 Answers

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());
}
like image 191
Ted Hopp Avatar answered Oct 03 '22 10:10

Ted Hopp


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());
like image 21
Sunimal S.K Malkakulage Avatar answered Oct 03 '22 11:10

Sunimal S.K Malkakulage