It is a Null Pointer Exception that comes with Java, but I wanted to get the value as safely as possible, so this time I tried the method of getting the value of Map.
Map<String, Boolean> map = new HashMap<String, Boolean>() {
{
put("true_label", true);
put("false_label", false);
put("null_label", null);
}
};
assertTrue(map.get("true_label"));
assertFalse(map.get("false_label"));
assertNull(map.get("null_label"));
assertNull(map.get("invalid_label")); //Keys that do not exist in Map
You can get an alternative value if you don't have the key.
assertTrue(map.getOrDefault("true_label", false));
assertFalse(map.getOrDefault("false_label", false));
assertFalse(map.getOrDefault("invalid_label", false)); //You can get an alternative value if you don't have the key.
assertNull(map.getOrDefault("null_label", false)); //Unfortunately it doesn't become false!!
assertTrue(Optional.ofNullable(map.get("true_label")).orElse(false));
assertFalse(Optional.ofNullable(map.get("false_label")).orElse(false));
assertFalse(Optional.ofNullable(map.get("null_label")).orElse(false)); //Alternate value false
assertFalse(Optional.ofNullable(map.get("invalid_label")).orElse(false)); //Alternate value false
Optional may be fine, but just in case
assertTrue(ObjectUtils.defaultIfNull(map.get("true_label"), false));
assertFalse(ObjectUtils.defaultIfNull(map.get("false_label"), false));
assertFalse(ObjectUtils.defaultIfNull(map.get("null_label"), false)); //Alternate value false
assertFalse(ObjectUtils.defaultIfNull(map.get("invalid_label"), false)); //Alternate value false
Recommended Posts