Skip to main content

APIzation: Replication Package

[Q#11009818][A#11009861] How to get list of Integer from String

https://stackoverflow.com/q/11009818

my string contains Integer separated by space: How I can get list of Integer from this string ?

Answer

https://stackoverflow.com/a/11009861

You can use a Scanner to read the string one integer at a time.

APIzation

Scanner scanner = new Scanner(number);
List<Integer> list = new ArrayList<Integer>();
while (scanner.hasNextInt()) {
    list.add(scanner.nextInt());
}
package com.stackoverflow.api;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Human11009861 {

  public static List<Integer> integerListFromNumberString(String number) {
    Scanner scanner = new Scanner(number);
    List<Integer> list = new ArrayList<Integer>();
    while (scanner.hasNextInt()) {
      list.add(scanner.nextInt());
    }
    return list;
  }
}

package com.stackoverflow.api;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * How to get list of Integer from String
 *
 * @author APIzator
 * @see <a href="https://stackoverflow.com/a/11009861">https://stackoverflow.com/a/11009861</a>
 */
public class APIzator11009861 {

  public static void getList(String number) throws Exception {
    Scanner scanner = new Scanner(number);
    List<Integer> list = new ArrayList<Integer>();
    while (scanner.hasNextInt()) {
      list.add(scanner.nextInt());
    }
  }
}