I wish to get a value from a HasMap but some time the value doesn't exist so I have done this:
int var = 0;
if (hashMapHouse.containsKey("home1") {
var = hashMapHouse.get("houme1");
}
if(var==0) //do something
else //do something else
My question is: is it possible to have one call of hashMap in order to get the value and to test if the value exist or no?
HashMap containsValue() Method in Java HashMap. containsValue() method is used to check whether a particular value is being mapped by a single or more than one key in the HashMap. It takes the Value as a parameter and returns True if that value is mapped by any of the key in the map.
The standard solution to check if a value exists in a map is using the containsValue() method, which returns true if the map maps one or more keys to the specified value. Note that if the value is an custom object, remember to override the equals and hashCode methods of that class.
containsKey() method is used to check whether a particular key is being mapped into the HashMap or not. It takes the key element as a parameter and returns True if that element is mapped in the map.
In Java 8 you can use the getOrDefault method:
int var = hashMapHouse.getOrDefault("home1", 0);
It's the cleanest solution, in a single line you can get either the value for the key if it exists, or a predefined default value to indicate that it doesn't exist - 0
in this case.
Sure
Integer houme = hashMapHouse.get("houme1");
if (null == houme ) {
// not exists
} else {
// exists
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With