Map Java Collection Tutorial

Map


  1. Stores values in key and value.
  2. map does not allow duplicate key.
  3. only one null key but any number of null values

To synchronize the Map use.

Collections.synchronizedMap(yourMapObject)

Hashmap

  1. Hashmap allows random storage sequence is not maintained.
  2. Stores values in key and value.
  3. Hashmap is not synchronized.
  4. Collections.synchronizedHashset
  5. Hashmap does not allow duplicate key.
  6. Hashmap allows only one null key but any number of null values.

To calculate hashcode we use key field.

package com.collection;
import java.util.HashMap;

import java.util.Map;

import java.util.Set;
public class HashMapExample {
public static void main(String[] args) {

Map<String,String> mapObj=new HashMap<>();
mapObj.put(“old”, “1”);

mapObj.put(“old”, “2”);//will replace 1 by 2 as duplicate keys not allowed.
//iterateAndPrint(mapObj);
//Output :Key is old Value is 2

mapObj.put(“latest”,”5″);//hashMap will not maintain insertion order.

mapObj.put(“new”,”3″);

mapObj.put(null,null);

mapObj.put(null,null);//HashMap can have only one null key and many values as null

System.out.println(“************Before Removing************”);

iterateAndPrint(mapObj);
mapObj.remove(“latest”);
System.out.println(“********After Removing************”);

iterateAndPrint(mapObj);

}
private static void iterateAndPrint(Map<String, String> mapObj) {

Set<String> keys=mapObj.keySet();

System.out.println();

for(String key:keys)

{

System.out.println(“Key is “+key+”| Value is “+mapObj.get(key));

}

System.out.println();

}
}

/*************Before Removing************
Key is null| Value is null

Key is new| Value is 3

Key is old| Value is 2

Key is latest| Value is 5
********After Removing************
Key is null| Value is null

Key is new| Value is 3

Key is old| Value is 2
*/


<C>TreeMap

  1. Internally TreeMap  implemented using red black tree concept on map.
  2. TreeMap sorts using the natural order that is ascending order
  3. TreeMap is used with comparator to sort key field using more than one attributes.

package com.collection;
import java.util.Map;

import java.util.Set;

import java.util.TreeMap;

/**

* 1.TreeMap is implmentation of SortedMap<I>

*/

public class TreeMapDemo {
public static void main(String[] args) {
Map<Integer,String> treeObj=new TreeMap<>();

treeObj.put(1, “Sam”);

treeObj.put(1000, “Zarin”);

treeObj.put(5, “Yak”);

treeObj.put(100, “Peter”);
Set<Integer> keySet=treeObj.keySet();

System.out.println();

System.out.println(“Before Remove”);

for(Integer oneKey:keySet)

{

System.out.println(“key=>”+oneKey+” Value is=>”+treeObj.get(oneKey));

}

System.out.println();
treeObj.remove(5);//removing element with key 5

System.out.println(“after Remove”);
iterateAndPrint(treeObj);
/************ADD DUPLLICATES****************/

System.out.println(“After Adding Duplicate”);

treeObj.put(100,”Peter”);

iterateAndPrint(treeObj);
/******ADD NULL *******************/

System.out.println(“After Adding NULL”);

treeObj.put(null,null);

iterateAndPrint(treeObj);
}

public static void iterateAndPrint(Map treeMapObj)

{

Set<Integer> keySet=treeMapObj.keySet();

for(Integer oneKey:keySet)

{

System.out.println(“key=>”+oneKey+” Value is=>”+treeMapObj.get(oneKey));

}

}
/******************OUTPUT******************************/

/*Before Remove

key=>1 Value is=>Sam

key=>5 Value is=>Yak

key=>100 Value is=>Peter

key=>1000 Value is=>Zarin
after Remove

key=>1 Value is=>Sam

key=>100 Value is=>Peter

key=>1000 Value is=>Zarin

After Adding Duplicate

key=>1 Value is=>Sam

key=>100 Value is=>Peter

key=>1000 Value is=>Zarin

After Adding NULL

Exception in thread “main” java.lang.NullPointerException

at java.util.TreeMap.put(TreeMap.java:563)

at com.collection.TreeMapDemo.main(TreeMapDemo.java:58)*/

}


Additional classes which are of least usgae 

PriorityBlockingQueue<C>

Collectrion<I>

      \

Queue<I>

\

PriorityBlockingQueue<C>

package com.collection;

import java.util.Iterator;

import java.util.List;

import java.util.Queue;

import java.util.concurrent.PriorityBlockingQueue;

public class QueueDemo {

public static void main(String[] args) {

Queue<String> queueObj=new PriorityBlockingQueue<>();

queueObj.add(“Shiv”); queueObj.add(“A”);

System.out.println(“POLL() Removes and shows element from the haed of queue”+queueObj.poll());

System.out.println(“PEEK() Will display element but won’t remove”+queueObj.peek());

System.out.println(“ADDS element and returns boolean “+queueObj.offer(“UI”));

iterateAndPrint(queueObj);

}

private static void iterateAndPrint(Queue listObj) {

Iterator<String> iteratorObj=listObj.iterator();

while(iteratorObj.hasNext())

{

System.out.println(“”+iteratorObj.next());

}

}

}

package com.collection;
import java.util.HashMap;

import java.util.Map;

import java.util.Set;

import java.util.WeakHashMap;

/**Rules:1.Null value as well as Null Key are permitted here.

* 2. used for cache also for lookup storage.

* 3.Entries if not used anywhere they can be removed at the same time this makes

* WeakHashMap efficient for garbage collection.

*

*

*

*

*/

public class WeakHashMapDemo {

public static void main(String[] args)

{

WeakHashMap<String, String> weakObj=new WeakHashMap<String,String>();

weakObj.put(“1”, “One”);

weakObj.put(“2”, “Two”);

for(int i=3;i<10;i++)

{

weakObj.put(“”+i, “Two”);

}

iterateAndPrint(weakObj);

System.out.println(“Value of Key 1 is “+weakObj.get(1));//If refernce not needed anymopre entry removed so

//output is null
}

public static void iterateAndPrint(Map treeMapObj)

{

@SuppressWarnings(“unchecked”)

Set<String> keySet=treeMapObj.keySet();
for(String oneKey:keySet)

{

System.out.println(“key=>”+oneKey+” Value is=>”+treeMapObj.get(oneKey));

}
}

}

/**

* OUtput

*key=>8 Value is=>Two

key=>9 Value is=>Two

key=>4 Value is=>Two

key=>5 Value is=>Two

key=>6 Value is=>Two

key=>7 Value is=>Two

key=>1 Value is=>One

key=>2 Value is=>Two

key=>3 Value is=>Two

Value of Key 1 is null

*

*

*/

WeakHashMap

Map<I>

\

WeakHashMap<C>

About weakHashMap

**Rules:1.Null value as well as Null Key are permitted here.

 * 2. used for cache also for lookup storage.

 * 3.Entries if not used anywhere they can be removed at the same time this makes

 * WeakHashMap efficient for garbage collection.

 *

 *

 *

 *

 */

package com.collection;
import java.util.HashMap;

import java.util.Map;

import java.util.Set;

import java.util.WeakHashMap;

/**Rules:1.Null value as well as Null Key are permitted here.

* 2. used for cache also for lookup storage.

* 3.Entries if not used anywhere they can be removed at the same time this makes

* WeakHashMap efficient for garbage collection.

*

*

*

*

*/

public class WeakHashMapDemo {

public static void main(String[] args)

{

WeakHashMap<String, String> weakObj=new WeakHashMap<String,String>();

weakObj.put(“1”, “One”);

weakObj.put(“2”, “Two”);

for(int i=3;i<10;i++)

{

weakObj.put(“”+i, “Two”);

}

iterateAndPrint(weakObj);

System.out.println(“Value of Key 1 is “+weakObj.get(1));//If refernce not needed anymopre entry removed so

//output is null
}

public static void iterateAndPrint(Map treeMapObj)

{

@SuppressWarnings(“unchecked”)

Set<String> keySet=treeMapObj.keySet();
for(String oneKey:keySet)

{

System.out.println(“key=>”+oneKey+” Value is=>”+treeMapObj.get(oneKey));

}
}

}

/**

* OUtput

*key=>8 Value is=>Two

key=>9 Value is=>Two

key=>4 Value is=>Two

key=>5 Value is=>Two

key=>6 Value is=>Two

key=>7 Value is=>Two

key=>1 Value is=>One

key=>2 Value is=>Two

key=>3 Value is=>Two

Value of Key 1 is null

*

*

*/

IdentityHashMap

Map<I>

\

IdentityHashMap<C>

For creating hashcode it uses System.identityHashCode(x) which generates hashcode.It does not uses

  1.   equals() and hashCode() for equality comparision between two objects.
  2.   It is having mandate to use key as Immutable objects (Immutable objects are those once created can not be changed.
  3.   If changed it creates new instance in memory.
  4.   Immutable classes provided by java
  5.   java.lang.Character,java.lang.Integer,, java.lang.Short, java.lang.Byte java.lang.Boolean, java.lang.Long, java.lang.Float, java.lang.Double,
  6.  Not Synchronized.ie.Concurrentmodification of this hashmap not allowed at all.
  7.  Nulls are allowed as key and value however if you add the null as key more than one time it replace it replacces the already existing key value pair.

package com.collection;
import java.util.IdentityHashMap;

import java.util.Map;

import java.util.Set;

//Rules:

/**

* 1.For creating hashcode it uses System.identityHashCode(x) which generates hashcode.It does not uses

* equals() and hashCode() for equality comparision between two objects.

* 2.It is having mandate to use key as Immutable objects (Immutable objects are those once created can not be changed.

* If changed it creates new instance in memory.

* Immutable classes provided by java

* java.lang.Character,java.lang.Integer,, java.lang.Short, java.lang.Byte java.lang.Boolean, java.lang.Long, java.lang.Float, java.lang.Double,

*3.Not Synchronized.ie.Concurrentmodification of this hashmap not allowed at all.

*4.Nulls are allowed as key and value however if you add the null as key more than one time it replace it replacces the already existing key value pair.

*/

public class IdentityHashMapDemo {
public static void main(String[] args) {

Map<String,String> maps=new IdentityHashMap<>();
maps.put(“1”, “one”);

maps.put(“2”, “two”);

iterateAndPrint(maps);

System.out.println();

System.out.println(“After adding null key and value as two”);

maps.put(null, “two”);

iterateAndPrint(maps);

System.out.println();

System.out.println(“After adding null key and value as three”);
maps.put(null, “three”);

iterateAndPrint(maps);

}

public static void iterateAndPrint(Map treeMapObj)

{

Set<String> keySet=treeMapObj.keySet();
for(String oneKey:keySet)

{

System.out.println(“key=>”+oneKey+” Value is=>”+treeMapObj.get(oneKey));

}

}

}

/**

* Output

* key=>1 Value is=>one

key=>2 Value is=>two
After adding null key and value as two

key=>1 Value is=>one

key=>null Value is=>two

key=>2 Value is=>two
After adding null key and value as three

key=>1 Value is=>one

key=>null Value is=>three

key=>2 Value is=>two
*

*

*/

Leave a Reply

Your email address will not be published. Required fields are marked *