Searching...
Saturday, 6 October 2012

Java Collections: HashMap Example

06:58
·         Stores key values pair, not allowed duplicate keys
·         Efficient in inserting (put()) and retrieving elements (get())
·         The order is not maintained
·         Unlike HashTable, HashMap’s methods are not synchronized

 
image
 

Example

package mycollectiontest;

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

public class CollectionExample {

public static void main(String[] args) {
Map<Integer, String> hMap = new HashMap<Integer, String>();
hMap.put(1, "Bangalore");
hMap.put(2, "Chennai");
hMap.put(3, "Cochin");
hMap.put(4, "Hydrabad");
// getting single value
System.out.println(hMap.get(1));

for (Entry<Integer, String> entry : hMap.entrySet()) {
System.out.println("Key " + entry.getKey() + " Value " + entry.getValue());

}
}

}

Output

Bangalore
Key 1 Value Bangalore
Key 2 Value Chennai
Key 3 Value Cochin
Key 4 Value Hydrabad

 

0 comments: