000webhost logo
/** * Created by PhpStorm. * User: Rahul * Date: 12/8/2016 * Time: 8:09 PM */ Map interface


Map Interface


Core Java

Interface Map ‹K,V ›

Type Parameters:
K - the type of keys maintained by this map V - the type of mapped values

If we want to represent a group of object as key-value pairs then we should go for map Interface.
In map both key and value are objects, in map Duplicate key are not allowed but Value can be duplicate. each key and value pair is consider as one entry object. Hence a set of entries is nothing but map.


Map is not Child interface of collection

A ClassCastException is thrown when an object is incompatible with the elements in a map.

A NullPointerException is thrown if an attempt is made to use a null object and null is not allowed in the map.

An UnsupportedOperationException is thrown when an attempt is made to change an unmodifiable map.


Methods available in Map with Description

	
	void clear( )
			//Removes all key/value pairs from the invoking map.

	boolean containsKey(Object k)
			//Returns true if the invoking map contains k as a key. Otherwise, returns false.
	
	boolean containsValue(Object v)
			//Returns true if the map contains v as a value. Otherwise, returns false.

	Set entrySet( )
			//Returns a Set that contains the entries in the map. The set contains objects of type Map.Entry. This method provides a set-view of the invoking map.

	boolean equals(Object obj)
			//Returns true if obj is a Map and contains the same entries. Otherwise, returns false.

	Object get(Object k)
			//Returns the value associated with the key k.

	int hashCode( )
			//Returns the hash code for the invoking map.

	boolean isEmpty( )
			//Returns true if the invoking map is empty. Otherwise, returns false.

	Set keySet( )
			//Returns a Set that contains the keys in the invoking map. This method provides a set-view of the keys in the invoking map.

	Object put(Object k, Object v)
			//Puts an entry in the invoking map, overwriting any previous value associated with the key. The key and value are k and v, respectively. Returns null if the key did not already exist. Otherwise, the previous value linked to the key is returned.

	void putAll(Map m)
			//Puts all the entries from m into this map.

	Object remove(Object k)
			//Removes the entry whose key equals k.

	int size( )
			//Returns the number of key/value pairs in the map.

	Collection values( )
			//Returns a collection containing the values in the map. This method provides a collection-view of the values in the map.


Since Map is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following Map implementations in the Java Collections API:


java.util.HashMap


java.util.Hashtable


java.util.EnumMap


java.util.IdentityHashMap


java.util.LinkedHashMap


java.util.Properties


java.util.TreeMap


java.util.WeakHashMap


the most commonly used Map implementations are HashMap and TreeMap.
Each of these Map implementations behaves a little differently with respect to the order of the elements when iterating the Map, and the time (big O notation) it takes to insert and access elements in the maps.
HashMap maps a key and a value. It does not guarantee any order of the elements stored internally in the map.
TreeMap also maps a key and a value. Furthermore it guarantees the order in which keys or values are iterated


Here are examples of how to create a Map instance : -


Map mapA = new HashMap();
Map mapB = new TreeMap();


Map have various classes here are few Example of how to Implement


Adding and Accessing and Removing - Elements


Adding an Element into Map

To add elements to a Map you call its put() method - examples:

		Map mapA = new HashMap();
		
		mapA.put("key1", "element 1");
		mapA.put("key2", "element 2");
		mapA.put("key3", "element 3");

The three put() calls maps a string value to a string key. You can then obtain the value using the key. To do that you use the get() method like this: String element1 = (String) mapA.get("key1");


Removing Elements

You remove elements by calling the remove(Object key) method. You thus remove the (key, value) pair matching the key.


Iterate on array

You can iterate either the keys or the values of a Map. Here is how you do that:

		// key iterator
		Iterator iterator = mapA.keySet().iterator();
		
		// value iterator
		Iterator iterator = mapA.values();
		Most often you iterate the keys of the Map and then get the corresponding values during the iteration. Here is how it looks:
		Iterator iterator = mapA.keySet().iterator();
		while(iterator.hasNext(){
		  Object key   = iterator.next();
		  Object value = mapA.get(key);
		}
		
		//access via new for-loop
		for(Object key : mapA.keySet()) {
		    Object value = mapA.get(key);
		}

Generic Maps

By default you can put any Object into a Map, but from Java 5, Java Generics makes it possible to limit the types of object you can use for both keys and values in a Map. Here is an example:

		Map <String, MyObject> map = new HashMap<String, MyObject>(); 
			//This Map can now only accept String objects for keys, and MyObject instances for values. 
			//You can then access and iterate keys and values without casting them. 
		
		for(MyObject anObject : map.values()){
		   //do someting to anObject...
		}
		
		for(String key : map.keySet()){
		   MyObject value = map.get(key);
			   //do something to value
		}

TreeMap -

The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. Below example you will notice that treeMap toString shows that entries are ordered by performing natural ordering on Int keys.

HashMap –

This class makes no guarantees as to the order of the map. Uses object equality to check if key already exist in map and replace value if it exist. As in example while trying to put key11 as it equals with key1 value “One” is replaced with “Eleven”.

IdentityHashMap -

Unlike above HashMap, this uses reference-equality in place of object-equality when comparing keys. As in following example even after key11 equals key1, but as their references are not equals so a new key/value is inserted.

LinkedHashMap –

This implementation keeps track of order in which keys were inserted into the map. In below example you will notice that the toString shows entries in same order in which they were inserted. This also has another feature discussed next.

LRU Caching using LinkedHashMap –

Another feature of LinkedHashMap is that it provide constructor to create a linked hash map whose order of iteration is the order in which its entries were last accessed, from least-recently accessed to most-recently (access-order). In following example, you will notice that when elements are inserted and none is accessed yet, the order of Entries is same as that of above example. But after accessing elements, you will notice that the entries order is changed based on when last it was accessed. Using this feature one can create a LRU(accessed) cache as shown in example. You will need to override removeEldestEntry method of LinkedHashMap and add your logic for caching. Each put operation will call this removeEldestEntry by passing least-recently-accessed element to it and based on removeEldestEntry’s return value it will either be kept or removed from the map.

WeakHashMap-

In this implementation keys are held as WeakReferences. This way if there is no strong reference for key, on next Garbage Collection this key and corresponding value will be removed from the Map. Read this article for details on Java References. As in below example we are adding three keys to map and then clearing one strong reference to key6 by setting it to null. Then we request GC by calling System.gc() and in next statement you will notice that the key/value for key6 is removed from Map.

An Example for Complete MAP-Inteface


package collections;

import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.WeakHashMap;

public class DemoMap {

    public static void main(String[] args) {
        // TreeMap
        Map treeMap = new TreeMap();
        treeMap.put(4, "Four");
        treeMap.put(1, "One");
        treeMap.put(5, "Five");
        treeMap.put(3, "Three");
        treeMap.put(2, "Two");
        System.out.println("TreeMap - " + treeMap);
        // TreeMap - {1=One, 2=Two, 3=Three, 4=Four, 5=Five}

        // HashMap
        Key key1 = new Key(1);
        Key key11 = new Key(1);
        Key key2 = new Key(2);
        Key key3 = new Key(3);
        Map map = new HashMap();
        map.put(key1, "One");
        map.put(key11, "Eleven");
        map.put(key2, "Two");
        map.put(key3, "Three");
        System.out.println("HashMap - " + map);
        // HashMap - {3=Three, 1=Eleven, 2=Two}

        // IdentityHashMap
        Map idMap = new IdentityHashMap();
        idMap.put(key1, "One");
        idMap.put(key11, "One");
        idMap.put(key2, "Two");
        idMap.put(key3, "Three");
        System.out.println("IdentityHashMap - " + idMap);
        // IdentityHashMap - {1=One, 1=One, 3=Three, 2=Two}

        // LinkedHashMap
        Map linkedMap = new LinkedHashMap(5);
        linkedMap.put(4, "Four");
        linkedMap.put(1, "One");
        linkedMap.put(5, "Five");
        linkedMap.put(3, "Three");
        linkedMap.put(2, "Two");
        System.out.println("LinkedHashMap - " + linkedMap);
        //LinkedHashMap - {4=Four, 1=One, 5=Five, 3=Three, 2=Two}
        
        // LinkedHashMap for Caching using access-order
        Map cachedLinkedMap = new CacheUsingLinkedHashMap(5);
        cachedLinkedMap.put(4, "Four");
        cachedLinkedMap.put(1, "One");
        cachedLinkedMap.put(5, "Five");
        cachedLinkedMap.put(3, "Three");
        cachedLinkedMap.put(2, "Two");
        System.out.println("LinkedHashMap at full capacity no access performed yet - " + cachedLinkedMap);
        // LinkedHashMap at full capacity no access performed yet - {4=Four, 1=One, 5=Five, 3=Three, 2=Two}
        cachedLinkedMap.get(1);
        cachedLinkedMap.get(2);
        cachedLinkedMap.get(4);
        cachedLinkedMap.get(5);
        cachedLinkedMap.get(3);
        System.out.println("LinkedHashMap at full capacity after accessing few elements - " + cachedLinkedMap);
        // LinkedHashMap at full capacity after accessing few elements - {1=One, 2=Two, 4=Four, 5=Five, 3=Three}
        cachedLinkedMap.put(6, "Six");
        System.out.println("LinkedHashMap after adding new entry - " + cachedLinkedMap);
        // As 1 is least recently accessed.
        // LinkedHashMap after adding new entry - {2=Two, 4=Four, 5=Five, 3=Three, 6=Six}

        // WeakHashMap
        Map weakMap = new WeakHashMap();
        Key key4 = new Key(4);
        Key key5 = new Key(5);
        Key key6 = new Key(6);
        weakMap.put(key4, "Four");
        weakMap.put(key5, "Five");
        weakMap.put(key6, "Six");
        System.out.println("WeakHashMap before GC - " + weakMap);
        // WeakHashMap before GC - {6=Six, 5=Five, 4=Four}
        key6 = null;
        System.gc();
        System.out.println("WeakHashMap after GC - " + weakMap);
        // WeakHashMap after GC - {5=Five, 4=Four}
    }

    static class CacheUsingLinkedHashMap extends LinkedHashMap {

        int capacity;

        public CacheUsingLinkedHashMap(int cap) {
            super(cap + 1, 1.1f, true);
            capacity = cap;
        }

        @Override
        protected boolean removeEldestEntry(java.util.Map.Entry eldest) {
            return size() > capacity;
        }

    }

    static class Key {
        int key;

        public Key(int key) {
            this.key = key;
        }

//In collection main page we already explain  more about overriding the hashCode() method
//If you havent seen yet go Through - http://javaessential.com/java-tut/collection.html
        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + key;
            return result;
        }
        
//In collection main page we already explain  more about overriding the equals() method
//If you havent seen yet go Through - http://javaessential.com/java-tut/collection.html
        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Key other = (Key) obj;
            if (key != other.key)
                return false;
            return true;
        }

//In collection main page we already explain  more about overriding the toString() method
//If you havent seen yet go Through - http://javaessential.com/java-tut/collection.html
        @Override
        public String toString() {
            return String.valueOf(key);
        }
    }

}
______________________  ignore the below line  __________________________

Map has its implementation in various classes With Example

import java.util.*;

public class CollectionsDemo {

   public static void main(String[] args) {
      Map m1 = new HashMap(); 
      m1.put("Prashant", "8");
      m1.put("Raheem", "31");
      m1.put("Harish", "12");
      m1.put("Ravi", "14");
      System.out.println();
      System.out.println(" Map Elements");
      System.out.print("\t" + m1);
   }
}

->  Output - Map Elements
        { Raheem=31, Harish=12, Ravi=14, Prashant=8 }

Following example showing how - Map.put(), Iterator,get() , getKey() ,entrySet() ,Map.Entry can be used:


import java.util.*;

public class HashMapDemo {

   public static void main(String args[]) {
      // Create a hash map
      HashMap hm = new HashMap();
      // Put elements to the map
      hm.put("Robin", new Double(3434.34));
      hm.put("Aditya", new Double(123.22));
      hm.put("Ashish", new Double(1378.00));
      hm.put("Kailash", new Double(99.22));
      hm.put("Joy", new Double(-19.08));
      
      // Get a set of the entries
      Set set = hm.entrySet();
      // Get an iterator
      Iterator i = set.iterator();
      // Display elements
      while(i.hasNext()) {
         Map.Entry me = (Map.Entry)i.next();
         System.out.print(me.getKey() + ": ");
         System.out.println(me.getValue());
      }
      System.out.println();
      // Deposit 1000 into Robin's account
      double balance = ((Double)hm.get("Robin")).doubleValue();
      hm.put("Robin", new Double(balance + 1000));
      System.out.println("Robin's new balance: " +
      hm.get("Robin"));
   }
}

 Output - 
Kailash 99.22
Joy: -19.08
Robin: 3434.34
Ashish: 1378.0
Aditya: 123.22
Robin.s current balance: 4434.34


Click here to continue reading - Set Interface