Monday, January 12, 2015

Java Using Hashmap Program



How to iterate through HashMap

package com.java2novice.hashmap; 
import java.util.HashMap;
import java.util.Set;

public class MyHashMapRead
{
public static void main(String a[])
{
        HashMap hm = new HashMap();
        hm.put("first", "First inserted");
        hm.put("second", "Second inserted");
        hm.put("third","Third inserted");
        System.out.println(hm);
        Set keys = hm.keySet();
        for(String key: keys)
        {
            System.out.println("Value of "+key+" is: "+hm.get(key));
        }
    }
}

How to copy Map content to another HashMap

package com.java2novice.hashmap;
import java.util.HashMap;
public class MyHashMapCopy
{
public static void main(String a[])
{
        HashMap hm = new HashMap();
        hm.put("first", "First inserted");
        hm.put("second", "Second inserted");
        hm.put("third","Third inserted");
        System.out.println(hm);
        HashMap subMap = new HashMap();
        subMap.put("s1", "S1 Value");
        subMap.put("s2", "S2 Value");
        hm.putAll(subMap);
        System.out.println(hm);
    }
}

How to search a key in HashMap

package com.java2novice.hashmap;
import java.util.HashMap;
public class MyHashMapKeySearch
{
public static void main(String a[])
{
        HashMap hm = new HashMap();
        hm.put("first", "First inserted");
        hm.put("second", "Second inserted");
        hm.put("third","Third inserted");
        System.out.println(hm);
        if(hm.containsKey("first"))
        {
            System.out.println("The hashmap contains key first");
        }
        else
      {
            System.out.println("The hashmap does not contains key first");
        }
        if(hm.containsKey("fifth"))
        {
            System.out.println("The hashmap contains key fifth");
        }
        else
      {
            System.out.println("The hashmap does not contains key fifth");
        }
    }
}

How to search a value in HashMap

package com.java2novice.hashmap;
import java.util.HashMap;
public class MyHashMapValueSearch
{
public static void main(String a[])
{
        HashMap hm = new HashMap();
        hm.put("first", "First inserted");
        hm.put("second", "Second inserted");
        hm.put("third","Third inserted");
        System.out.println(hm);
        if(hm.containsValue("Second inserted"))
        {
            System.out.println("The hashmap contains value Second inserted");
        }
        else
      {
System.out.println("The hashmap does not contains value Second inserted");
        }
        if(hm.containsValue("first"))
        {
            System.out.println("The hashmap contains value first");
        }
        else
      {
            System.out.println("The hashmap does not contains value first");
        }
    }
}

No comments:

Post a Comment