Reputation: 423
For example, say I have the following String: "1 23 35 5d 8 0 f"
When I run the function, how can I extract an ArrayList<Integer>
out of it so it will contain {1, 23, 35, 8, 0}
, effectively skipping invalid integers?
If anything, the skipping invalid integers is not very important, as I can easily resolve that, but I'm mainly trying to see if there's an effective way to parse every integer from a String.
Upvotes: 1
Views: 232
Reputation: 6739
public class Agent{
public static void main(String...args){
String input = "1 23 35 5d 8 0 f";
List<Integer> intList = new ArrayList<Integer>();
Arrays.asList(input.split(" ")).stream().forEach( i -> {
try{
intList.add(Integer.parseInt(i));
}catch(Exception ex){
}
});
intList.forEach( i -> System.out.print(" " + i));
}
}
Output:
1 23 35 8 0
Upvotes: 0
Reputation: 737
I would use a regex, the easy one would simply be to remove all non numeric/space characters, then simply split the string
Edit:
As pointed out in the comments this solution does not give the answer the questioner wanted. OK, an actual solution for this would be split the string on spaces then use a regex to insure all the digits in each string are numeric. This actually insures that not only are all the items numeric, but because we are also filtering out the . character the numbers in each of these are integers, there is no need to check the int at this point and it can simply be parsed
Upvotes: 1
Reputation: 50021
Nothing fancy. Just loop, and ignore exceptions:
List<Integer> list = new ArrayList<>();
for (String num : "1 23 35 5d 8 0 f".split(" ")) {
try {
list.add(Integer.parseInt(num));
} catch (NumberFormatException e) {}
}
*Edit*: If invalid integers are common, you will get better performance using a manual check of the digits of each part:
List<Integer> list = new ArrayList<>();
outer:
for (String num : "1 23 35 5d 8 0 f".split(" ")) {
for (int i = 0; i < num.length(); i++) {
char c = num.charAt(i);
if (!((c >= '0' && c <= '9') || c == '-' || c == '+')) continue outer;
}
try {
list.add(Integer.parseInt(num));
} catch (NumberFormatException e) {}
}
This still has the try-catch in order to reject out of range integers or any that have minus/plus signs in inappropriate places, but you can remove that if you know those don't occur in your data, or if you'd prefer to throw the exception for those cases.
Upvotes: 2
Reputation: 10945
If you don't want to write your own "is this a number" checker, you can use Apache Commons:
List<Integer> list = new ArrayList<>();
for (String num : "1 23 35 5d 8 0 f".split(" ")) {
if (StringUtils.isNumeric(num)) {
list.add(Integer.parseInt(num));
}
}
This has the advantage of not using exception handling to do flow control (which I find inelegant).
Upvotes: 2