Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to treat keys of HashMap as optional in java [duplicate]

While using Map as a function argument, only values for 3 keys are populated. However when this function is invoked in another function, the user populates values for initial 2 keys and he does not require 3rd key to be assigned with any value. However if 3rd key is not assigned any value then, the 3rd key is display null value.

Is there any way to avoid this. if user does not assign any value to 3rd key, it must be empty instead of null value.

     public String setMapValues(Map<String,String> testMap) throws Exception
  {
    String str="";

    str= testMap.get("a");
    str+=testMap.get("b");
    str+=testMap.get("c");

    info(str);

    return str;
  }



    public void run() throws Exception 
    {
    LinkedHashMap<String,String> myMap = new LinkedHashMap<String,String>();
    myMap.put("a", "James");
    myMap.put("b", "Bond");
    this.setMapValues(myMap);
}

The function calls displays JamesBondnull as the output, instead it should only display JamesBond as the output by ignoring/skipping the null at the end.

like image 636
Steve Avatar asked Feb 16 '23 20:02

Steve


2 Answers

You can use a function like

static String nullAsEmpty(Object o) {
   return o == null ? "" : o.toString();
}

public String setMapValues(Map<String,String> testMap) {
    String str = nullAsEmpty(testMap.get("a")) +
                 nullAsEmpty(testMap.get("b")) +
                 nullAsEmpty(testMap.get("c"));

    info(str);

    return str;
}
like image 75
Peter Lawrey Avatar answered Feb 19 '23 10:02

Peter Lawrey


How about:

String temp = testMap.get("c");
str+= (temp == null : "" : temp);
like image 20
BobTheBuilder Avatar answered Feb 19 '23 11:02

BobTheBuilder