Home > Java > javaTutorial > 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

王林
Release: 2020-05-15 10:49:38
Original
6723 people have browsed it

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

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!

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