Setting default values ​​in HashMap

I am trying to find a way to return the default HashMap value. For example, if you look at the following, it will be a printout of " Test: = null ", if I want to request a default value, so anytime I try to get something that is NOT set in hashMap, will I get a value?

Map<String, String> test = new HashMap<String, String>(); test.put("today","monday"); System.out.println("Test =:" + test.get("hello") + ""); 
+4
source share
5 answers

It is better to check the return value instead of changing the way Map IMO works. The Commons Lang method StringUtils.defaultString(String) 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 here .

+4
source

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")); 
+7
source

Instead of trying to give meaning to the data, why don't you just check if you want to extract the data?

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

No, you cannot use it as a switching condition. You can override the get method by extending it to another class, or you can 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")); 

You can also achieve this simply by using the Properties class instead of the 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 
+2
source

Extend the HashMap and override get() .

0
source

Source: https://habr.com/ru/post/1487349/


All Articles