If HashMap Java exists, it gets the value

I want to get a value from hasmap, but sometimes the value does not exist, so I did this:

int var = 0;
if (hashMapHouse.containsKey("home1") {
    var = hashMapHouse.get("houme1");
}
if(var==0) //do something
else //do something else

My question is: can I call HashMap to get the value and test whether the value exists?

Solution

In Java 8, you can use the getordefault method:

int var = hashMapHouse.getOrDefault("home1",0);

This is the cleanest solution. In a single line, you can get the value of the key (if it exists), or a predefined default value to indicate that it does not exist - in this case, 0

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>