snorlax snorlax - 1 year ago 130
Java Question

HashMap Java get value if it is exist

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download