Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Default Values in HashMap [duplicate]

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") + "");
like image 560
user2428795 Avatar asked Dec 05 '22 10:12

user2428795


2 Answers

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"));
like image 176
Arno Mittelbach Avatar answered Dec 28 '22 04:12

Arno Mittelbach


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.

like image 31
Spiff Avatar answered Dec 28 '22 03:12

Spiff