Search code examples
javahashmapguavalookup

Extract value of the key from a map basis on a priority?


I have a map of String and String. I want to extract key value and assign it to another String variable but in a priority order.

  • If abc key is present, then assign value of abc to clientId variable and we are done.
  • Buf if abc key is not present, then look for this key pqr and assign value of pqr to clientId variable and we are done.
  • But if pqr key is also not present, then look for this key def and assign value of def to clientId variable and we are done.
  • But if none of those keys are present, then value of clientId will be null.

Below is the code:

Map<String, String> holderMap = populateHolderMap<>();
String clientId = null;

if (!holderMap.isEmpty()) {
  clientId = holderMap.get("abc");
  if (Strings.isNullOrEmpty(clientId)) {
    clientId = holderMap.get("pqr");
    if (Strings.isNullOrEmpty(clientId)) {
      clientId = holderMap.get("def");
    }
  }
}

Is there any better way to write this thing? Or may be one liner using ternary operator?

There is a possibility that all three keys can be present or two keys can be present and I always have to stick to my order only. If abc key is present, then we will use that no matter whether other keys are presents or not.


Solution

  • Please go for code readability over lesser lines of code. what you have is fine.

    Using ternary operator: The syntax is condition ? if_condition_true : if_condition_false;

    if (!holderMap.isEmpty()) {
      clientId = holderMap.get("abc") == null ? 
                 holderMap.get("pqr") == null ? 
                 holderMap.get("def") == null ? 
                 null : holderMap.get("def") : holderMap.get("pqr") : holderMap.get("abc");
    }
    

    Using if and else if

    if (!holderMap.isEmpty()) {
        if( holderMap.get("abc") != null ) {
           clientId = holderMap.get("abc");
        } else if ( holderMap.get("pqr") != null ) {
           clientId = holderMap.get("pqr");
        } else if (holderMap.get("def") != null ) {
           clientId = holderMap.get("def");
        }
    }