The idea of this post is to just highlight some of the features in Java which we may need in our day to day development work.
- The different ways to check null value of an Object
- null != obj
- Objects.nonNull(obj) - from java.util
- filter(Objects::nonNull) - when used with Lambda
- Optional.ofNullable(obj).ifPresent(o —> o.getValue());
- StringUtils.isNotEmpty(obj) - from org.apache.commons.lang3
- this takes care of both empty and null checks
- filter(StringUtils::isNotEmpty) - when used with Lambda
- Do something if nonNull and something else if Null
- Optional.ofNullable(obj).map(obj -> {doSomething(obj)return obj;}).orElseGet(() -> {logForNull();return null;});Here, If the object is nonNull, then only the value will be applied to the mapping function
No comments:
Post a Comment