java program to create a hashmap and access the element
import java.util.*;
public class HashMapExample {
public static void main(String[] args) {
//creating a HashMap
HashMap<Integer,String> map=new HashMap<Integer,String>();
//adding element to HashMap
map.put(1,"Mango");
map.put(2,"Orange");
map.put(3,"Banana");
System.out.println("Iterating map :");
//printing element by using for loop
for(Map.Entry m:map.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
//adding element if not present in hashmap
map.putIfAbsent(4,"Papaya");
System.out.println();
for(Map.Entry m:map.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
System.out.println();
HashMap<Integer,String> hashmap=new HashMap<Integer,String>();
//copying element of one hashmap to another
hashmap.putAll(map);
for(Map.Entry m:hashmap.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
//printing hashmap
System.out.println();
System.out.println(hashmap);
}
}