Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does googles guava have a java tryparse integer method or something similar?

Tags:

java

guava

I have the java guava library, and was wondering if they have a tryparse type helper method that will attempt to parse a string to a integer, and return a boolean if it failed.

In c#, I can do:

if(int.tryparse("somestring", out myInt)) {

}

Was hoping java has something similiar (don't want to re-invent the wheel if it exists).

like image 934
Blankman Avatar asked Jan 28 '12 04:01

Blankman


2 Answers

Guava has Ints.tryParse(String) as of 11.0. It doesn't work quite like the C# method (no out parameters) though. It returns an Integer that's null if the string couldn't be parsed, so for your example you'd use it like this:

Integer myInt = Ints.tryParse(someString);
if (myInt != null) {
  ...
}
like image 200
ColinD Avatar answered Nov 04 '22 15:11

ColinD


It looks like this was set to be added to release 11. The status is set to fixed, which I would think means it's either in the current release or will be in the next.

http://code.google.com/p/guava-libraries/issues/detail?id=660

EDIT: It is in the API for 11: tryParse

like image 39
James Montagne Avatar answered Nov 04 '22 14:11

James Montagne