my string contains Integer separated by space:
String number = "1 2 3 4 5 "
How I can get list of Integer from this string ?
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());
}
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.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());
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);
}
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) );
}
split it with space, get an array then convert it to list.
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();
}
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 "".