Sunday, September 2, 2018

Do you know - Series 1: Null Check: Java

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) - froorg.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 -> {
          return obj;
      }).orElseGet(() -> {
          return null;

      HereIf the object is nonNull, then only the value will be applied to the mapping function

No comments:

Post a Comment

Do you know - Series - 4: Boxing and Unboxing - Integer assignment and comparison

We know about boxing and unboxing in Java. It is about automatic conversion of primitive type value into its Wrapper Object equivalent type...