Home > Java > JavaBase > body text

How to determine whether key exists in map collection in java

王林
Release: 2019-12-02 09:12:00
Original
6002 people have browsed it

How to determine whether key exists in map collection in java

有两种方法可以判断map集合中是否存在某个key。

方法1:直接使用java api提供的containsKey()

方法2:循环遍历,逐个比较。

java相关视频推荐:java视频

具体实现代码如下:

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("存在");
			} 
		}
	}
 
}
Copy after login

java相关文章教程推荐:java开发入门

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template