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

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


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

V get(Object key) This method gives back a 'value' of the specified key if the underlying map contains mapping for that key otherwise returns 'null'

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

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

Syntax

V get(Object key)

This method gives back a 'value' of the specified key if the underlying map contains mapping for that key otherwise returns 'null'.

In this method a returned value will be 'null' if the underlying map has an association of 'null' value with a key, this does not mean that the underlying map has no association for a specified key. This operation may be distinguished by using the containsKey() method of this (Map) interface.

Parameter description

V : It is the type of parameter in map

Key : It takes key from (key-value) mappings which you want to get the value.

Example of get(Object key) method

In this example we will show you how does get(Object key) method work in Map interface. This example will help you to understand how you can get the value of a specified key. In this example we will also show you how can we distinguish the returning of null values in different conditions as it is explained above.

Example :

package devmanuals.com;
import java.util.Map;
import java.util.HashMap;
public class MapGet {
  public static void main(String args[]){
    Map mp =new HashMap();
    mp.put(1"A");
    mp.put(2"B");
    mp.put(3"C");
    mp.put(4"D");
    mp.put(5null);
    System.out.println("Mappings are : "+mp);
    boolean bol=mp.containsKey(4);
    System.out.println("does the key 4 mappings into this map : "+bol);
    System.out.println("Value of the key '4' is : "+mp.get(4));
    bol=mp.containsKey(5);
    System.out.println("does the key 5 mappings into this map : "+bol);
    System.out.println("Value of the key '5' is : "+mp.get(5));
    bol=mp.containsKey(6);
    System.out.println("does the key 6 mappings into this map : "+bol);
    System.out.println("Value of the key 6 is : "+mp.get(6));
  }
}

Output :

Mappings are : {1=A, 2=B, 3=C, 4=D, 5=null}

does the key 4 mappings into this map : true

Value of the key '4' is : D

does the key 5 mappings into this map : true

Value of the key '5' is : null

does the key 6 mappings into this map : false

Value of the key 6 is : null

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


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

 
Tutorial Topics