Home  >  Article  >  Java  >  How to determine whether a certain key exists in the map collection in java

How to determine whether a certain key exists in the map collection in java

王林
王林Original
2020-05-15 10:49:386631browse

How to determine whether a certain key exists in the map collection in java

Generally, we will use two methods to make judgments, namely:

1. Directly use the containsKey() method provided by java api;

2. Loop through and compare one by one.

(Recommended video tutorial: java video)

Specific code:

import java.util.Iterator;
import java.util.Map;
 
import com.google.common.collect.Maps;
 
public class MapTest {
 
	public static void main(String[] args) {
		
		Map<String, String> map = Maps.newHashMap();
		map.put("1", "1");
		map.put("2", "2");
		map.put("3", "3");
		map.put("4", "4");
		
		//方法1
		System.out.println(map.containsKey("5"));
		
		//方法2
		Iterator keys = map.keySet().iterator();
		String key;
		while(keys.hasNext()){
			key = (String) keys.next();
			if ("1".equals(key)) {
				System.out.println("存在");
			} 
		}
	}
 
}

Recommended tutorial: java entry program

The above is the detailed content of How to determine whether a certain key exists in the 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