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") + "");
user2428795
  • 547
  • 6
  • 11
  • 26

5 Answers5

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"));
blackpanther
  • 10,998
  • 11
  • 48
  • 78
Arno Mittelbach
  • 952
  • 5
  • 12
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.

Spiff
  • 2,266
  • 23
  • 36
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);
}
Daniel
  • 2,435
  • 5
  • 26
  • 40
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
Visruth
  • 3,430
  • 35
  • 48
0

Extend the HashMap and override the get().

AllTooSir
  • 48,828
  • 16
  • 130
  • 164