I am trying to find a way to make a HashMap return a default value. For example if you look at the following this will printout "Test:=null" what if I want to request a default value so anytime I try to get something that is NOT set in the hashMap I will get the value?
Map<String, String> test = new HashMap<String, String>();
test.put("today","monday");
System.out.println("Test =:" + test.get("hello") + "");
Try the following:
Map<String,String> map = new HashMap<String,String>(){
@Override
public String get(Object key) {
if(! containsKey(key))
return "DEFAULT";
return super.get(key);
}
};
System.out.println(map.get("someKey"));
Better check the return value instead of changing the way a Map
works IMO. The Commons Lang StringUtils.defaultString(String)
method should do the trick:
Map<String, String> test = new HashMap<>();
assertEquals("", StringUtils.defaultString(test.get("hello")));
assertEquals("DEFAULT", StringUtils.defaultString(test.get("hello"), "DEFAULT"));
StringUtils JavaDoc is here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With