4

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") + "");
1
  • Override the Map. Note this will break the contract. Commented Jun 20, 2013 at 18:17

5 Answers 5

8

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"));
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

2

Rather than try to give a value to the data, why don't you just do a check when you want to pull the data?

if (!set.containsKey(key)){
    return default_value;
}
else{
    return set.get(key);
}

Comments

2

No, you can't use it as a switch condition. You can override the get method by extending it into another class or you may try it as follows :

Map<String, String> test = new HashMap<String, String>();
test.put("today", "monday");
String s = test.get("hello") == null? "default value" : test.get("hello");
System.out.println("Test =:" + s);

or

    final String defaultValue = "default value";
    Map<String, String> test = new HashMap<String, String>() {

        @Override
        public String get(Object key) {
            String value = super.get(key);
            if (value == null) {
                return defaultValue;
            }
            return value;
        };
    };
    test.put("today", "monday");            
    System.out.println("Test =:" + test.get("nokey"));

And also you can achieve this by simply using Properties class instead of HashMap.

        Properties properties = new Properties();
        properties.setProperty("key1", "value of key1");
        String property1 = properties.getProperty("key1", "default value");
        String property2 = properties.getProperty("key2", "default value");
        System.out.println(property1);
        System.out.println(property2);

which prints :

value of key1
default value

Comments

0

Extend the HashMap and override the get().

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.