I have an application where I need to handle a lot of numbers (Integers or Longs) comming from external sources.
The numbers can be null. In case they are null I always need to convert them to 0.
The problem seems trivial, but I don't want to write hundreds of times:
if (someNumber == null) {
someNumber = 0;
}
I don't like it for two reasons:
- I don't like to write three lines of code for such simple task, especially because I need to do it many times
- I don't like to to "mutate" someNumber (assign new value to someNumber variable)
I tried some other ways which can be seen here:
public static void main(String[] args) {
Integer zeroOrNull = new Random().nextBoolean() ? 0 : null;
// version1: this is nasty (I already mentioned why)
if (zeroOrNull == null) {
zeroOrNull = 0;
}
// version2: this seems to much for so simple task...
zeroOrNull = Optional.ofNullable(zeroOrNull).orElseGet(() -> 0);
// version3: creating an util might be considerable. Is there already such predefined util ?
zeroOrNull = MyUtil.getValueOrZero(zeroOrNull); // returns value or )
System.out.println(zeroOrNull); // I want 0 here in case of null
}
What is the preffered and nice way to do such "test for null/conversion to 0" ? Any chance to do this conversion implicitly?
This is my original answer, if "efficient" was intended only by "performance" I've wronged word, sorry.
The mean is that all coding process is better, develop and execution are more safe.
http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html