Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IntegerUtils and DoubleUtils in Apache Commons package

I use the Apache Commons package extensively, especially the StringUtils, BooleanUtils, ObjectUtils, MapUtils classes and find them extremely helpful. I am wondering if there are classes such as IntegerUtils, DoubleUtils that provide a similar functionality for their respective wrapper classes (I do not find such classes in the Apache Commons package).

Thanks,

Venkat

like image 341
Venk K Avatar asked Mar 28 '13 22:03

Venk K


1 Answers

I wish they had a utilities class for numbers as useful as the one for strings. NumberUtils class is all about converting numbers to/from strings.

You can use ObjectUtils to do null-safe Integer operations though.

Instead of:

foo(Integer arg) {
  if(arg != null && arg == 1)
    doSomething();
}

You can do:

foo(Integer arg) {
  if(ObjectUtils.defaultIfNull(arg, 0) == 1)
    doSomething();
}

In the case where the Integer you are comparing is, say, a function call that returns an Integer, this will allow you to only call the function once without creating a throwaway variable.

like image 185
Kip Avatar answered Sep 26 '22 14:09

Kip