11

my string contains Integer separated by space:

String number = "1 2 3 4 5 "

How I can get list of Integer from this string ?

1

13 Answers 13

24

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());
}
Sign up to request clarification or add additional context in comments.

5 Comments

Just one question is this method faster or slower then method mention in other answers ?
All these examples will run in O(n) time. So the answer is there is no real performance difference. Edit: Actually, splitting the strings first like (suggested in another post), and then adding them to a collection will contain 2 x O(n) loops. This solution would be better
@hudi - I think that my code compares favorably in terms of speed with the other answers, but that can only be determined by profiling. The differences will be small.
@TedHopp - How about the String "2a11b20c"?? I would like to get the result list [2, 11, 20]. Thanks :-)
@ZinMinn - Well, you could call scanner.useDelimiter("\\D"); which would tell the scanner to consider anything other than a digit as a delimiter. It would then treat the "a", "b", and "c" in your sample string the same as blanks and you could still use hasNextInt() and nextInt() as in my answer.
14
ArrayList<Integer> lst = new ArrayList<Integer>();
for (String field : number.split(" +"))
    lst.add(Integer.parseInt(field));

With Java 8+:

List<Integer> lst = 
    Arrays.stream(number.split(" +")).map(Integer::parseInt).collect(Collectors.toList());

Comments

7
String number = "1 2 3 4 5";
String[] s = number.split("\\s+");

And then add it to your list by using Integer.parseInt(s[index]);

List<Integer> myList = new List<Integer>();
for(int index = 0 ; index<5 ; index++)
             myList.add(Integer.parseInt(s[index]);

Comments

6

In Java 8 you can use streams and obtain the conversion in a more compact way:

    String number = "1 2 3 4 5 ";
    List<Integer> x = Arrays.stream(number.split("\\s"))
            .map(Integer::parseInt)
            .collect(Collectors.toList());

Comments

3

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());

1 Comment

what's the difference between first and second method?
1

Firstly,using split() method to make the String into String array.

Secondly,using getInteger() method to convert String to Integer.

Comments

1
 String number="1 2 3 4 5";
 List<Integer> l=new ArrayList<Integer>();
 String[] ss=number.split(" ");
 for(int i=0;i<ss.length;i++)
 {
   l.add(Integer.parseInt(ss[i]));
 }

System.out.println(l);

Comments

1

Simple solution just using arrays:

// variables
String nums = "1 2 3 4 5";
// can split by whitespace to store into an array/lits (I used array for preference) - still string
String[] num_arr = nums.split(" ");
int[] nums_iArr = new int[num_arr.length];
// loop over num_arr, converting element at i to an int and add to int array

for (int i = 0; i < num_arr.length; i++) {
    int num_int = Integer.parseInt(num_arr[i])
    nums_iArr[i] = num_int
}

That pretty much covers it. If you wanted to output them, to console for instance:

// for each loop to output
for (int i : nums_iArr) {
      System.out.println(i);
}

1 Comment

Okay, simple modification: First for loop: Sub out the int num_int for nums_iArr = Integer.parseInt(num_arr[i]) Drops a line of code. Is that enough or would you suggest something more?
1

I would like to introduce tokenizer class to split by any delimiter. Input string is scanned only once and we have a list without extra loops.

    String value = "1, 2, 3, 4, 5";
    List<Long> list=new ArrayList<Long>();
    StringTokenizer tokenizer = new StringTokenizer(value, ",");
    while(tokenizer.hasMoreElements()) {
        String val = tokenizer.nextToken().trim();
        if (!val.isEmpty()) list.add( Long.parseLong(val) );
    }

Comments

0

split it with space, get an array then convert it to list.

3 Comments

when I convert array to list with method asList I get array of string not Integer
@hudi you can convert those string to integer using 'Integer.parseInt()' method
I dont like this method becaue when in this string isnt number then occurs exceptions and I looking for some faster method to convert this not one by one
0

You can split it and afterwards iterate it converting it into number like:

    String[] strings = "1 2 3".split("\\ ");
    int[] ints = new int[strings.length];
    for (int i = 0; i < strings.length; i++) {
        ints[i] = Integer.parseInt(strings[i]);
    }
    System.out.println(Arrays.toString(ints));

Comments

0

You first split your string using regex and then iterate through the array converting every value into desired type.

String[] literalNumbers = [number.split(" ");][1]
int[] numbers = new int[literalNumbers.length];

for(i = 0; i < literalNumbers.length; i++) {
    numbers[i] = Integer.valueOf(literalNumbers[i]).intValue();
}

Comments

0

I needed a more general method for retrieving the list of integers from a string so I wrote my own method. I'm not sure if it's better than all the above because I haven't checked them. Here it is:

public static List<Integer> getAllIntegerNumbersAfterKeyFromString(
        String text, String key) throws Exception {
    text = text.substring(text.indexOf(key) + key.length());
    List<Integer> listOfIntegers = new ArrayList<Integer>();
    String intNumber = "";
    char[] characters = text.toCharArray();
    boolean foundAtLeastOneInteger = false;
    for (char ch : characters) {
        if (Character.isDigit(ch)) {
            intNumber += ch;
        } else {
            if (intNumber != "") {
                foundAtLeastOneInteger = true;
                listOfIntegers.add(Integer.parseInt(intNumber));
                intNumber = "";
            }
        }
    }
    if (!foundAtLeastOneInteger)
        throw new Exception(
                "No matching integer was found in the provided string!");
    return listOfIntegers;
}

The @key parameter is not compulsory. It can be removed if you delete the first line of the method:

    text = text.substring(text.indexOf(key) + key.length());

or you can just feed it with "".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.