View RSS Feed

Algorithm and Data Structure

Adding and Accessing Map Elements

Rate this Entry
by , 02-19-2012 at 07:24 AM (1054 Views)
For addition of elements to Map, use put() method. This process is explained by the given code.
Java Code: This is the code to explain map add operation
Map mapA = new HashMap();
mapA.put("key1", "element 1");
mapA.put("key2", "element 2");
mapA.put("key3", "element 3");
Key values are mapped by calling 3 put() methods, in the code given above. Both values & keys are String, in above code. To get value, use this code.
Java Code: This is the code to explain map access operation
String element1 = (String) mapA.get("key1");
Values are retrieved from Map by using get() method. A key will be provided and Map would be returning the corresponding value.

Iteration could also be performed on Map by using value or key iteration. This is explained by this code.
Java Code: This is the code to explain map iteration
// key iterator
Iterator iterator = mapA.keySet().iterator();
// value iterator
Iterator iterator = mapA.values();
Also you can iterate the keys and get the corresponding values based on these keys.
Iterator iterator = mapA.keySet().iterator();
while(iterator.hasNext(){
  Object key   = iterator.next();
  Object value = mapA.get(key);
}
//access via new for-loop
for(Object key : mapA.keySet()) {
    Object value = mapA.get(key);
}

Submit "Adding and Accessing Map Elements" to Facebook Submit "Adding and Accessing Map Elements" to Digg Submit "Adding and Accessing Map Elements" to del.icio.us Submit "Adding and Accessing Map Elements" to StumbleUpon Submit "Adding and Accessing Map Elements" to Google

Categories
Hashmap

Comments