Map Implementations

Map:




1.The java.util.Map interface represents a mapping between a key and a value. The Map interface is not a subtype of the Collection interface. Therefore it behaves a bit different from the rest of the collection types.

2.when if we want get elements based on some key best choice is Map implementation classes

3.duplicates keys are not allowed but value can be duplicated .if key already
available then old value replaced with new value and return old value. 
Entery(Interface):
Each key value pair is called one enterys hence map is a group entery objets .
2.With out existing Map object there is no chance of existing Entery object
because Entery interface defined inside map interface.
interface Map{
interface Entery{
Object getKey();
Object getValue();
Object setValue(Object obj);
}
}

Map Implementations:

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.IdentityHashMap
java.util.LinkedHashMap
java.util.Properties
java.util.TreeMap
java.util.WeakHashMap
In my experience, 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 - which is the sort order of the keys or values. Check out the JavaDoc for more details.
Here are a few examples of how to create a Map instance:
Map mapA = new HashMap();
Map mapB = new TreeMap();

HashMap:

1.The underlying datastrusture is HashTable .duplicates keys are not allowed but values can be duplicated .
2.Insertion order is not preserved .
3. Hetrogenous objects are  allowed for both  key and values

Example:

package com.collections;


import java.util.HashMap;

iport java.util.Set;

public class HashSetExample {

public static void main(String[] args) {

HashMap<Integer,String> cityCodes=new HashMap<Integer, String>();

cityCodes.put(10, "delhi");

cityCodes.put(20, "hyderbad");

cityCodes.put(30, "chennai");

cityCodes.put(40, "bangalore");

cityCodes.put(50, "kolkata");

cityCodes.put(60, "pune");

System.out.println(cityCodes);

//iterating map

Set<Integer>codes=cityCodes.keySet();

for(Integer code:codes){

System.out.println(cityCodes.get(code)+":::city by code");

}

}

}

output:

{50=kolkatha, 20=hyderbad, 40=bangalore, 10=delhi, 60=pune, 30=chennai}
kolkatha:::city by code
hyderbad:::city by code
bangalore:::city by code
delhi:::city by code
pune:::city by code
chennai:::city by code

java.util.Hashtable:

HasMap and HashTable both are use same method diffrence is
HashTable                                                                            HashMap
1.Every method in HasTable is synchronized      1.no method present in HashMap is synchronized    

 2.at a time
only one thread is allowed to operate on HashTable 2.multiple  threads can operate simultaneously hence its
hence it's thred safe.                                                   not thread safe
3.relatively performance is low                              3.relatively performance is high


java.util.LinkedHashMap:

it's child class of HashMap it's exactly same as HashMap main difference is it preserve insertion order.



java.util.IdentityHashMap:

It's also similar to HashMap difference is .in HashMap while adding elements it's check key values using
.equals method whether key is exist or not.
in IdentityHashMap it checks using "=="  operator whether key exist or not.
 


java.util.WeakHashMap:

we can replace above HashMap example using

WeakHashMap<Integer,String> cityCodes=new WeakHashMap<Integer, String>();

Methods for both are same difference is in the case of HashMap,even though object doesn't have any external references it's not eligible for garbage collector it it's associated with HashMap ie,HashMap
dominates garbagecollector .
But in case of WeakHasMap even though object associate with HashMap it's eligible for garbage collector
it it's does not contain any references ie,garbage collector dominates WeakHashMap.

java.util.TreeMap:

1.It's implementation of SorteMap.if you want to represents a group of key value pairs according to some sorting order of keys then we should go for TreeMap.

2.duplicates key are not allowed .
3.Insertion order is not preserved and it's based on some sorting order of keys
4.if we are depending default sorting order the keys should be homogeneous
and Comparable other wise we will get ClassCastException.
5.other wise we can define our own sorting order using Compartor
Example: 


package com.collections;
import java.util.TreeMap;
public class TreeMapExample {
public static void main(String[] args) {
TreeMap<Integer, String> oceansList = new TreeMap<Integer, String>(); oceansList.put(4, "Southern"); oceansList.put(1, "Pacific"); oceansList.put(5, "Arctic"); oceansList.put(3, "Indian"); oceansList.put(2, "Atlantic"); System.out.println("First ocean is::::"+oceansList.get(1)); System.out.println(oceansList);
}}



output:

First ocean is::::Pacific
{1=Pacific, 2=Atlantic, 3=Indian, 4=Southern, 5=Arctic}


Integer class implements Comparable so it follows default sorting order.


We can define our own sorting order using Comparator
Example:


package com.collections;
import java.util.Comparator;
import java.util.TreeMap;
public class TreeMapCustomizedSortingExample implements Comparator<Integer> {
public static void main(String[] args) {
TreeMap<Integer, String> oceansList = new TreeMap<Integer, String>(
new TreeMapCustomizedSortingExample());
oceansList.put(4, "Southern");
oceansList.put(1, "Pacific");
oceansList.put(5, "Arctic");
oceansList.put(3, "Indian");
oceansList.put(2, "Atlantic");
System.out.println("First ocean key is::::" + oceansList.firstKey());
System.out.println(oceansList);
}
@Override
public int compare(Integer ocean1, Integer ocean2) {
/*if (ocean1 > ocean2) {
return -1;
} else if (ocean1 < ocean2) {
return +1;
} else {
return 0;
}*/
/*simplified manner*/
return -ocean1.compareTo(ocean2);
}
}

java.util.Properties:

If any thing which changing frequently in our application like server url and database details
are not good program to hardcode in java program
Because for every change in java program we need to re compile and rebuild and re deploy ther application.
which creates big business impact.
To over come this problem we should go for properties file.
       We have to configure the required properties in the properties file and we have to read the properties file from our java program.
Advantage of this approach any change in properties file no need recompile or re build only
re deployment is enough .
 we are this java.util.Properties object to hold the properties .Properties is child class of HashTable
Properties can be used to represent as key value pairs where key and value should be String type.
Example:

package com.collections;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.util.Properties;

public class PropertiesExample {

public static void main(String[] args) {

Properties properties = new Properties(); 

FileInputStream stream; 

try {  

stream = new FileInputStream("D:/prgnew/Collections/src/db.properties"); properties.load(stream); 

catch (FileNotFoundException e) {

e.printStackTrace(); 

catch (IOException e) { 

e.printStackTrace();

}  

System.out.println("url of databse is::" + properties.getProperty("url")); System.out.println("username of databse is::" + properties.getProperty("username")); System.out.println("password of databse is::" + properties.getProperty("password")); 

}}

output:

url of databse is::jdbc:oracle:thin:@localhost:1521:XE

username of databse is::scoot

password of databse is::tiger







  

Author

Written by Admin

Aliquam molestie ligula vitae nunc lobortis dictum varius tellus porttitor. Suspendisse vehicula diam a ligula malesuada a pellentesque turpis facilisis. Vestibulum a urna elit. Nulla bibendum dolor suscipit tortor euismod eu laoreet odio facilisis.

0 comments: