Home >Java >javaTutorial >How to determine whether key exists in map collection in java?

How to determine whether key exists in map collection in java?

青灯夜游
青灯夜游Original
2020-08-20 14:45:037641browse

Java method to determine whether the specified key exists in the map collection: 1. Use the containsKey() method to determine; if it exists, it returns true, if it does not exist, it returns false. 2. Use loop traversal, compare one by one, and make judgments.

How to determine whether key exists in map collection in java?

Recommended: "Java Video Tutorial"

In java, sometimes you will encounter the map passed by the judgment Whether the specified key is included, there are two methods: <br>

Method 1: Loop through and compare one by one

HashMap map = new HashMap();  
map.put("1", "value1");  
map.put("2", "value2");  
Iterator keys = map.keySet().iterator(); 
while(keys.hasNext()){  
     String key = (String)keys.next();
     if("2".equals(key)){  
        System.out.println("存在key");  
     }  
}

Method 2: Directly Use the containsKey()

#map provided by the java api. Map is a collection of key-value pairs of key and value. If there are key and value pairs, there will be a way to determine whether there is a key. This method is the containsKey method. <br>

boolean flag=map.containsKey("opt")

For example:

if(map.containsKey("name")){
value=map.get("name").toString();
System.out.println("找到了name的值:"+value);
}

The containsKey(key) method in map can determine whether the key is in the map There is presence. Returns true if exists. Returns false if it does not exist.

For more programming-related knowledge, please visit: Introduction to Programming! !

The above is the detailed content of How to determine whether key exists in map collection in java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn