Map delete/remove

In this chapter you will learn:

  1. How to remove key and value pair
  2. How to remove all key and value pair from a Map

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;
/*from ja v a  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");
    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;
/*  j  av a  2s  .c o 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:

  1. How to compare two Map
Home » Java Tutorial » Map
Map interface
Map element adding
Map.Entry class
Map key
Map value
Map key/value search
Map delete/remove
Map comparison
HashMap Class
HashMap search
HashMap clone
TreeMap
TreeMap key
TreeMap head sub map
TreeMap tail sub map
TreeMap sub map
NavigableMap
NavigableMap key
NavigableMap key-value pair
LinkedHashMap Class
IdentityHashMap
SortedMap