how to create a HashMap using collections in java
Previous | Home | Next |
In the following example we will see how to create a HashMap using collections.
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 put(Object key, Object value) method on the object of the HashMap for adding the elements to the HashMap. The general form of the put() method is,
put(Object key, Object value)
This method puts the specified value with the specified key in the method to the HashMap.
In the following example we have created a HashMap which have the keys in String format and the values are in the Integer format. Then we have used the put(Object key, Object value) method on the the HashMap object i.e hm(in this example).
Finally we have displayed the HashMap thus created.
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.put("one-> ", 1); // inserting values to the hashmap
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: ");
Iterator<String> itr=hm.keySet().iterator(); // Invoking iterator on the hashmap's keyset to retrieve the keys
while(itr.hasNext())
{
System.out.println(itr.next()); // displaying the keys in the hashMap
}
System.out.println("The values contained corresponding to the key are as follows: ");
Iterator<Integer> itr1=hm.values().iterator(); // Invoking iterator on the hashMap's elements
while(itr1.hasNext())
{
System.out.println(itr1.next()); //displaying the elements of 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:
two->
one->
five->
three->
four
The values contained corresponding to the key are as follows:
2
1
5
3
4
Previous | Home | Next |