Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap Java get value if it exists

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?

like image 657
snorlax Avatar asked Nov 19 '16 14:11

snorlax


People also ask

How do you check if value already exists in HashMap?

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.

How do you check if a value is present in a list of map Java?

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.

How do you check if an element is present in a HashMap in Java?

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.


2 Answers

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.

like image 101
Óscar López Avatar answered Sep 21 '22 17:09

Óscar López


Sure

Integer houme = hashMapHouse.get("houme1");

if (null == houme ) {
    // not exists 
} else {
    // exists 
} 
like image 38
OneCricketeer Avatar answered Sep 19 '22 17:09

OneCricketeer