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
source share