how to use the Map.Entry interface on the HashMap using collections in java
Previous | Home | Next |
In this example we shall see how can we use the Map.Entry interface on the HashMap.
For creating a HashMap first of all we have to import the java.util package in which the java.util.HashMap class is contained which is used for creating the HashMap. In this example we have created a class named CollectionExample in which we have created HashMap and added some elements to it.
In this example we have used the Map.Entry interface, and then we have used separately accessed the keys and values of the HashMap by using getKey() and getValue() method on the map object.
In this example we have created a HashMap and then added some elements to it. We have also created a Set of the elements of the HashMap using the entrySet() method on the HashMap object i.e hm. Then we have used the iterator() method of the Iterator interface on the set. We have created an reference of the Map.Entry interface and typecasted the values returned by the iterator to Map.Entry. Then finally we have displayed the values contained in the Map.Entry reference object by using the getKey() and getValue() methods.
package r4r.co.in;
import java.util.*;
public class CollectionExample {
/**
* @param args
*/
public static void main(String args[]) throws IllegalArgumentException, NullPointerException
{
try
{
HashMap<String, Integer> hm = new HashMap<String, Integer>(); // creating a HashMap hm
hm.put("one-> ", 1); // adding value to the HashMap on key value pair
hm.put("two-> ", 2);
hm.put("three-> ", 3);
hm.put("four-> ", 4);
hm.put("five-> ", 5);
System.out.println("The key contained in the HashMap are as follows: ");
Set set=hm.entrySet(); // creating a set of the key-value pairs contained in the HashMap
Iterator itr=set.iterator(); // Invoking iterator on the HashMap
System.out.println("The key value pair in contained in the hashmap are as follows: ");
while(itr.hasNext())
{
Map.Entry<String, Integer> m = (Map.Entry<String, Integer>)itr.next(); // Using Map.Entry Interface
String key=(String)m.getKey(); // retrieving the keys contained the map entry interafce object
Integer value=(Integer)m.getValue(); // retrieving the keys contained in the map entru interface object
System.out.print(key); // displaying the keys contained in the HashMap
System.out.println(value); // displaying the values contained in the HashMap
}
}
catch(NullPointerException e)
{
e.printStackTrace();
}
catch(IllegalArgumentException e)
{
e.printStackTrace();
}
}
}
The output of the above given example is as follows:
The key contained in the HashMap are as follows:
The key value pair in contained in the hashmap are as follows:
two-> 2
one-> 1
five-> 5
three-> 3
four-> 4
Previous | Home | Next |