Map key/value search
In this chapter you will learn:
Map key search
We can check if a key is inside a Map. containsKey
returns true
if a key is there, it returns false
if a key is not
there.
import java.util.HashMap;
import java.util.Map;
//from j a va 2 s . com
public class Main{
public static void main(String[] a) {
Map<String,String> map = new HashMap<String,String>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
System.out.println(map.get("key2"));
System.out.println(map.containsKey("key2"));
System.out.println(map.containsKey("key4"));
}
}
The code above generates the following result.
Value existence in a Map
To see if a value is contained in a Map use containsValue
.
import java.util.HashMap;
import java.util.Map;
/*j a va 2s. co m*/
public class Main {
public static void main(String[] a) {
Map<String,String> map = new HashMap<String,String>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
System.out.println(map.containsKey("key1"));
System.out.println(map.containsValue("value2"));
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Collections