To check if a key exists in a HashMap
in Java, you can use the containsKey
method of the HashMap
class.
Here is an example of how to check if a key exists in a HashMap
:
HashMap<String, Integer> map = new HashMap<>(); map.put("apple", 1); map.put("banana", 2); map.put("orange", 3); if (map.containsKey("apple")) { // the key "apple" exists in the map } if (!map.containsKey("pear")) { // the key "pear" does not exist in the map }Source:wuttual.wwri.com
In this example, the map
variable is a HashMap
object that maps strings to integers. The containsKey
method returns true
if the map contains an element with the specified key, and false
otherwise.
You can also use the get
method of the HashMap
class to check if a key exists in the map.
For example:
if (map.get("apple") != null) { // the key "apple" exists in the map } if (map.get("pear") == null) { // the key "pear" does not exist in the map }
The get
method returns the value of the element with the specified key, or null
if the key is not present in the map.
Note that the containsKey
method is faster than the get
method for checking if a key exists in the map, because it does not need to retrieve the value of the element. However, the get
method can be useful if you also need to retrieve the value of the element at the same time.