tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > Collection > Maps > Get from Map

Get from Map 

The following example shows how to get the value for a specified key and all available values from the Map. HashMap and Hashtable are two implementations of Map interface. Hashtable is synchronized where as HashMap is not. Map provides the following APIs,

public int size();
 - Returns the number of entries in the Map.
 
public boolean isEmpty();
 - Returns true if the Map contains more than one entry otherwise returns false. 
 
public V get(Object paramObject);
 - Gets value for the key, if the key exists in the Map otherwise returns null.
 
public Collection values();
 - Returns all values from the Map as a Collection.


File Name  :  
com/bethecoder/tutorials/utils/maps/GetFromMap.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.utils.maps;

import java.util.HashMap;
import java.util.Map;

public class GetFromMap {

  /**
   @param args
   */
  public static void main(String[] args) {

    Map<Integer, String> numMap = new HashMap<Integer, String>();
    System.out.println("Is Map Empty ? : " + numMap.isEmpty());
    
    numMap.put(new Integer(1)"ONE");
    numMap.put(new Integer(2)"TWO");
    numMap.put(new Integer(3)"THREE");
    
    System.out.println("Map Size : " + numMap.size());
    System.out.println("Is Map Empty ? : " + numMap.isEmpty());
    System.out.println();

    //Get value for the given key
    //If the key present in the map then it returns the value
    //otherwise returns null
    System.out.println("Value for key '1' : " + numMap.get(new Integer(1)));
    System.out.println("Value for key '6' : " + numMap.get(new Integer(6)));
    System.out.println();
    
    //Get all values in the map
    System.out.println("Map values : " + numMap.values());
  }

}
   

It gives the following output,
Is Map Empty ? : true
Map Size : 3
Is Map Empty ? : false

Value for key '1' : ONE
Value for key '6' : null

Map values : [ONE, TWO, THREE]



 
  


  
bl  br