Java - Check Not Null/Empty else assign default value

147,708

Solution 1

I know the question is really old, but with generics one can add a more generalized method with will work for all types.

public static <T> T getValueOrDefault(T value, T defaultValue) {
    return value == null ? defaultValue : value;
}

Solution 2

Use Java 8 Optional (no filter needed):

public static String orElse(String defaultValue) {
  return Optional.ofNullable(System.getProperty("property")).orElse(defaultValue);
}

Solution 3

If using JDK 9 +, use Objects.requireNonNullElse(T obj, T defaultObj)

Solution 4

Use org.apache.commons.lang3.StringUtils

String emptyString = new String();    
result = StringUtils.defaultIfEmpty(emptyString, "default");
System.out.println(result);

String nullString = null;
result = StringUtils.defaultIfEmpty(nullString, "default");
System.out.println(result);

Both of the above options will print:

default

default

Solution 5

You can use this method in the ObjectUtils class from org.apache.commons.lang3 library :

public static <T> T defaultIfNull(T object, T defaultValue)
Share:
147,708

Related videos on Youtube

Cam1989
Author by

Cam1989

Updated on March 31, 2022

Comments

  • Cam1989
    Cam1989 about 2 years

    I am trying to simplify the following code.

    The basic steps that the code should carry out are as follows:

    1. Assign String a default value
    2. Run a method
    3. If the method returns a null/empty string leave the String as default
    4. If the method returns a valid string set the String to this result

    A Simple example would be:

        String temp = System.getProperty("XYZ");
        String result = "default";
        if(temp != null && !temp.isEmpty()){
            result = temp;
        }
    

    I have made another attemp using a ternary operator:

        String temp;
        String result = isNotNullOrEmpty(temp = System.getProperty("XYZ")) ? temp : "default";
    

    The isNotNullOrEmpty() Method

     private static boolean isNotNullOrEmpty(String str){
        return (str != null && !str.isEmpty());
    }
    

    Is it possible to do all of this in-line? I know I could do something like this:

    String result = isNotNullOrEmpty(System.getProperty("XYZ")) ? System.getProperty("XYZ") : "default";
    

    But I am calling the same method twice. I would be something like to do something like this (which doesn't work):

    String result = isNotNullOrEmpty(String temp = System.getProperty("XYZ")) ? temp : "default";
    

    I would like to initialize the 'temp' String within the same line. Is this possible? Or what should I be doing?

    Thank you for your suggestions.

    Tim

    • Holger
      Holger almost 3 years
      System.getProperty("XYZ", "default")
  • hagrawal
    hagrawal almost 9 years
    @fge Lets say it is not case of System.getProperty() but some method which doesn't have this extra parameter for default value. Then trick will work, it is scalable.
  • Cam1989
    Cam1989 almost 9 years
    How did I make this so complicated!? Thank you very much! I have used the getValueOrDefault() method. Great answer.
  • Q8i
    Q8i almost 8 years
    WOW! Compared to swift's s = q ?? r.
  • Cam1989
    Cam1989 almost 7 years
    Thanks shibashis. I still use this code and have a method for lots of object types! I will try with generics instead to simplify the code. Thank you
  • Jon Skeet
    Jon Skeet almost 7 years
    @Cam1989: This doesn't answer the question you asked though, because it doesn't handle empty strings... it only deals with the value being null, not empty... if that's what you wanted, that's what you should have asked. This is a perfectly good solution to a different problem, but it is a solution to a different problem...
  • Steve Goossens
    Steve Goossens over 6 years
    it would meet the empty requirement by replacing "value == null" with "isNotNullOrEmpty(value)" and switching value and defaultValue in the ternary responses
  • Ryan Burbidge
    Ryan Burbidge almost 5 years
    Optionals should not be created for flow control within a method. This is called out as an anti-pattern by the developers who built Optional. youtube.com/watch?amp=&v=Ej0sss6cq14
  • PAX
    PAX over 4 years
    @RyanBurbidge, and the reason: You unnecessarily create an object in your simple method (Optional object).
  • jmm
    jmm almost 4 years
    This checks for null, but not for empty Strings. It's better to use StringUtils.defaultIfBlank instead
  • brunch875
    brunch875 over 3 years
    Careful! While the ternary operator itself is lazy, this solution isn't! Which means a call to myThing = getValueOrDefault(thing, new Thing()); will create and discard that new Thing() if thing is not null. You may want to adapt this function to take a lambda instead so you may do getValueOrDefault(thing, Thing::new) instead.
  • brunch875
    brunch875 over 3 years
    @PAX, if that's the only reason you can avoid it by using Optional::orElseGet instead. I personally prefer the ternary operator since it's just as lazy and shorter.
  • Pavel
    Pavel about 3 years
    @RyanBurbidge, nice reference, thanks! Relevant part of the video: 27:44 - 30:00
  • kap
    kap about 3 years
    Great method, finally we got it. It's a shame it does not do automatic int to long casting.
  • Holger
    Holger almost 3 years
    @Q8i of course, if you make an operation unnecessarily complicated, you want to max it out. As otherwise, you could simply use System.getProperty("property", defaultValue) that does the job without additional syntactic constructs.
  • Holger
    Holger almost 3 years
    @brunch875 Since Java 9, this functionality exist as standard API method: Objects.requireNonNullElse(T obj, T defaultObj), including a variant with lazy construction of the fallback, Objects.requireNonNullElseGet(T obj, Supplier<? extends T> supplier).
  • rendon
    rendon over 2 years
    I don't know why this solution is so popular, it's quite verbose.
  • Pierre C
    Pierre C about 2 years
    There is also StringUtils.defaultIfBlank to provide a default if the string is null or blank (e.g. contains spaces only) : result = StringUtils.defaultIfBlank(emptyString, "default");.