Saturday 31 December 2011

Java HashMap

The Hash Map uses <Key, value> pair to store data. The Key is unique for each data in a map. There can be one NULL key in a map.
Class Name:  HashMapExample.java
import java.util.*;

public class HashMapExample1 {
       public static void main(String[] args) {
              Map<String,Integer> map1 = new HashMap<String,Integer>();
      
              //Map to store name and age Map<Key,Value>
              map1.put("SAM", 18);
              map1.put("DONALD", 26);
              map1.put("BILLY", 24);
              map1.put("TRINITY", 18);
              map1.put("JIM", null);
              map1.put(null, 24);
              System.out.println("Contents of Map : "+map1);
             
              //KeySet() returns all key in the Map
              System.out.println("Keyset : "+map1.keySet());
             
              //Remove a value from map
              map1.remove("JIM");
              System.out.println("Contents of Map after removing : "+map1);
             
              //Getting particular value using key
              System.out.println("Value of map at given KEY : "+map1.get("SAM"));
             
              //Size of map
              System.out.println("Size of the give map : "+map1.size());
             
              //Getting all values in the map
              System.out.println("Values in map : "+map1.values());
             
              //To check if the map is empty - returns true if map is empty
              System.out.println("Is the map empty : "+map1.isEmpty());
       }
}
OUTPUT:
Contents of Map : {null=24, DONALD=26, SAM=18, TRINITY=18, JIM=null, BILLY=24}
Keyset : [null, DONALD, SAM, TRINITY, JIM, BILLY]
Contents of Map after removing : {null=24, DONALD=26, SAM=18, TRINITY=18, BILLY=24}
Value of map at given KEY : 18
Size of the givem map : 5
Values in map : [24, 26, 18, 18, 24]
Is the map empty : false

No comments:

Post a Comment