Friday, November 2, 2012

Maps in Java

Here is a simple program which shows how to use Maps in Java


package com.giri.test;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;


/* Map Example:
 * Map interface is a part of java.util package.
 * Map interface can add key and value pair elements - put(key,value)
 * This map permits NULL value.
 * Map *is* interface
 * 
 */
public class MapTest {
 
 public static void main(String[] args) {
  
  Integer[] intArray = { 1,2,3,4,5 };
  
  Map my_map = new HashMap();

my_map.put(new Integer(1), "one");
my_map.put(new Integer(2), "HolyCow");
my_map.put(new Integer(3), "May the force be with you !");

Set my_set = my_map.entrySet();

Iterator it = my_set.iterator();

while(it.hasNext()) {
Map.Entry m = (Map.Entry) it.next();

// getKey is used to get the key of the map
int key = (Integer) m.getKey();

// getValue is used to get the value of the key in the map
String value = (String) m.getValue();

System.out.println("\n Key: " + key + " , Value : " + value);
}

}

}


Output:

 Key: 1 , Value : one

 Key: 2 , Value : HolyCow

 Key: 3 , Value : May the force be with you !

No comments :

Post a Comment