I have two pieces of code like below:
code 1:
Optional.fromNullable(integerVsLongMap.get(id)).or(getDefaultLong());
and
code 2:
integerVsLongMap.contains(id) ? integerVsLongMap.get(id) : getDefaultLong();
I would like to know which piece of code is more efficient and preferable in terms of space and time complexity and in terms of coding practices, cause what I see is both do the same thing?
integerVsLongMap? If not, (2) is the only correct way to do it, since there may be a null value in the map. Correctness should trump efficiency and readability. If using Java 8, useMap.getOrDefault.