Map is a set of collection that allows to store element with its key. that is, it allows us to store key-value pairs in the collection. Keys are used to retrive the associated element and we can find quickly any element in the colloection using key. In java library provides to further implemetnation of Map interface, i.e. HashMap and TreeMap. HashMap hashes the keys and TreeMap uses total ordering on the Keys to organize them in a search tree. Hashing is applied only on the keys, not on values. Every time you add an object to map , youhave to provide key for that object.

HashMap :

 This class provides all of the map operations, and allows null values and the null key.
 It is unsynchronized.
 Order is not maintained.

  •  It has to parameters: initial capacity and load factor.
  •  The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created.
  •  The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased.
  •  When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.

There are following construtor to create HashMap

HashMap(int initialCapacity)
HashMap(int initialCapacity, float loadFactor)
HashMap(Map m)

package collection.demos;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HashMapDemo {
    public static void main(String[] args) {
        Map<String,Long> phoneNumbers=new HashMap<String,Long>();
        //Putting values in HashMap
        System.out.println("Values : "+phoneNumbers);
        //getting value for specific key
        System.out.println("Value of key xyz : "+phoneNumbers.get("xyz"));
        //checking for specific key
        System.out.println("There is a value of key xyz "+phoneNumbers.containsKey("xyz"));
        //checking for specific Object
        System.out.println("There is a value 453453344L "+phoneNumbers.containsValue(453453344L));
        //getting collection of values
        Collection<Long> phones=phoneNumbers.values();
        System.out.println("Collection values : "+phones);
        System.out.println("Size of HashMap : "+phoneNumbers.size());
       //Removing the element associated with specified key
        System.out.println("Values after removed : "+phoneNumbers);

        //Getting set of keys
        Set<String> keys=phoneNumbers.keySet();
        System.out.println("Set of Keys : "+keys);

        //Getting entryset of mappings
        Set<Map.Entry<String,Long>> entryset=phoneNumbers.entrySet();
        System.out.println("Entry set : "+entryset);
        //Removing all entries
        System.out.println("Values after cleared : "+phoneNumbers);


No comments:

Popular Posts