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());
}
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());
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]);
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());
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());
用空格分割它,得到一个数组然后将其转换为列表。
Firstly,using split()
method to make the String into String array.
Secondly,using getInteger()
method to convert String to Integer.
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);
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) );
}
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));
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 "".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.