In addition to Objects.firstNonNull , Guava 10.0 added the Optional class as a more general solution to this type of problem.
An Optional is something that may or may not contain a value. There are various ways to create an Optional instance, but the Factory Optional.fromNullable(T) method is suitable for your case.
Once you have Optional , you can use one of the or methods to get a value that contains Optional (if it contains a value) or some other value (if it isn't).
Combining all this, your simple example would look like this:
T value = Optional.fromNullable(obj).or(defaultValue);
Added optional flexibility if you want to use Supplier for the default value (so that you do not do calculations to get it if necessary) or if you want to bind several optional values together to get the first value that is present, for example:
T value = someOptional.or(someOtherOptional).or(someDefault);
ColinD Nov 07 '11 at 17:36 2011-11-07 17:36
source share