remove(Object key) method of Map Interface in Java.

remove(Object key) method of Map Interface in Java.


Posted in : Core Java Posted on : February 18, 2011 at 8:36 PM Comments : [ 0 ]

In this section we will discuss how can remove(Object key) method be implemented in Map interface in java. V remove(Object key) This method deletes the association for a key from the underlying map if it is present.

remove(Object key) method of Map Interface in Java.

In this section we will discuss how can remove(Object key) method be implemented in Map interface in java.

Syntax 

V remove(Object key) 

This method deletes the association for a key from the underlying map if it is present.

This method deletes a specific key association 'k' to value 'v' from the key-value set of the underlying map if this association exist into the map.In this method the value is returned to which the underlying map antecedently associated the key or, returns 'null' if the underlying map does not contain mapping for the specified key. If in the underlying map a key mappings a 'null' value and the remove method is implemented on that key, it returns 'null' this does not mean that the map contained no mapping for the key, it may be possible that the map explicitly mapped the key to 'null'.

Parameter description

V : It is the type parameter in map.

Key : It takes key as parameter which mapping do you want to remove from the underlying map.

Example of remove(Object key) method

In this example we will show you how does remove(Object key) method work in Map interface. This example will help you to understand how you can remove the mapping for a specified key from the underlying map.

Example :

package devmanuals.com;
import java.util.Map;
import java.util.HashMap;
public class MapRemove {
  public static void main(String args[]) {
    Map<Integer, String> mp = new HashMap<Integer, String>();
    mp.put(1"A");
    mp.put(2"B");
    mp.put(3"C");
    mp.put(4"D");
    mp.put(5null);
    System.out.println("Mapping = " + mp);
    System.out.println("Size of map = " + mp.size());
    String st = mp.remove(1);
    System.out.println("The removed element is " + st);
    st = mp.remove(5);// Output will be 'null'
    // This null shows there is a null mapping for key '5'.
    System.out.println("The removed element is " + st);
    st = mp.remove(6);// Output will be 'null'
    // This null shows there is no mapping for a key '6'.
    System.out.println("The removed element is " + st);
    System.out.println("Now Mapping = " + mp);
    System.out.println("Size of map = " + mp.size());
  }
}

Output :

Mapping = {1=A, 2=B, 3=C, 4=D, 5=null}

Size of map = 5

The removed element is A

The removed element is null

The removed element is null

Now Mapping = {2=B, 3=C, 4=D}

Size of map = 3

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics