Map delete/remove
In this chapter you will learn:
Remove key value pair
Pairs in a Map can be removed. A key value pair can be removed by calling
remove
method and pass in the key.
import java.util.HashMap;
import java.util.Map;
//j ava2 s. c om
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");
map.remove("key3");
System.out.println(map);
}
}
The code above generates the following result.
From the result we can see that the key3-value3
pair is removed
from the map.
Remove all key and value pair
We can also choose to remove all key-value pairs in a map.
clear()
method Map
removes all pairs in a map.
import java.util.HashMap;
import java.util.Map;
//from j a v a 2 s . 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");
map.clear();
System.out.println(map);
}
}
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Collections