Objects.isNull is intended for use within Java 8 lambda filtering.
It's much easier and clearer to write:
.stream().filter(Objects::isNull)
than to write:
.stream().filter(x -> x == null).
Within an if statement, however, either will work. The use of == null is probably easier to read but in the end it will boil down to a style preference.
Videos
Objects.isNull is intended for use within Java 8 lambda filtering.
It's much easier and clearer to write:
.stream().filter(Objects::isNull)
than to write:
.stream().filter(x -> x == null).
Within an if statement, however, either will work. The use of == null is probably easier to read but in the end it will boil down to a style preference.
should use object == null over Objects.isNull() in a if statement?
If you look at the source code of IsNull method,
/* Returns true if the provided reference is null otherwise returns false.*/
public static boolean isNull(Object obj) {
return obj == null;
}
It is the same. There is no difference. So you can use it safely.
From the JavaDoc of the method:
API Note: This method exists to be used as a
Predicate,filter(Objects::isNull)
Elaborating the above answer further with an example. Given a list of strings, Objects.isNull and Objects.nonNull can be used to filter out the null and non null values respectively from the list.
List<String> stringList = Arrays.asList("T", null, "S");
// Filter out all the elements that are not null.
stringList.stream().filter(Objects::nonNull).collect(Collectors.toList()); // "T","S"
// Filter out all the null elements.
stringList.stream().filter(Objects::isNull).collect(Collectors.toList()); // null