Java Check for Null References
In Java we can check for null pointer references using below approaches. If you ask me why we have to do this, is to avoid NullPointerException
.
Traditional way
public static List<Integer> getPrices (List<Integer> allPrices) {
if (allPrices == null) {
return Collections.EMPTY_LIST;
}
}
Use declarative approach
Before directly jumping into this, I want to share the methods we have to check for null referencs
- Objects.isNull()
- Objects.nonNull()
These methods we use in functional approach.
import java.util.List;
import java.util.Objects;
public class Sum {
public static Integer getSumOfCollection(List<Integer> num) {
Integer result = 0 ;
if (Objects.isNull(num)) {
return result;
}
return num.stream().
filter(Objects::nonNull).
mapToInt(Integer::intValue).
sum();
}
}
When you call this method with below inputs
System.out.println(Sum.getSumOfCollection(Arrays.asList(1,2,3,4,5)));
System.out.println(Sum.getSumOfCollection(Arrays.asList(1,null,2,null)));
it will handle the null
references gracefully and exclude them.
You can do the same in another approach
return num.stream()
.filter( eachNum -> eachNum != null)
.mapToInt(Integer::intValue)
.sum();
full code used for testing
Main.java
import java.util.Arrays;
import java.util.Optional;
class Main {
public static void main(String[] args) {
String name = null;
try {
{
method2();
throw new NullPointerException("name is null");
}
} catch(NullPointerException e) {
e.printStackTrace();
} finally {
System.out.println(Sum.getSumOfCollection(Arrays.asList(1,2,3,4,5)));
System.out.println(Sum.getSumOfCollection(Arrays.asList(1,null,2,null)));
System.out.println(Sum.getSumOfCollInteger(Arrays.asList(1,2,3,4,5)));
System.out.println(Sum.getSumOfCollInteger(Arrays.asList(1,null,2,null)));
}
}
public static void method2() {
String name2 = null;
Optional<String> optionalStr = Optional.ofNullable(name2);
if (!optionalStr.isPresent()) {
throw new NullPointerException("name2 is null references");
}
}
}
Sum.java
import java.util.List;
import java.util.Objects;
public class Sum {
public static Integer getSumOfCollection(List<Integer> num) {
Integer result = 0 ;
if (Objects.isNull(num)) {
return result;
}
return num.stream().
filter(Objects::nonNull).
mapToInt(Integer::intValue).
sum();
}
public static Integer getSumOfCollInteger(List<Integer> num) {
Integer result = 0 ;
if ( Objects.isNull(num)) {
return result;
}
return num.stream()
.filter(eachInt -> eachInt != null)
.mapToInt(Integer::intValue)
.sum();
}
}
Hope it helps. Thanks.