3. Map
• A Map stores data in key and value association. Both key and
values are objects. The key must be unique but the values can
be duplicate.
• The Java platform contains three general-
purpose Map implementations: HashMap, TreeMap,
and LinkedHashMap. (Their behavior and performance are
precisely analogous to HashSet, TreeSet, and LinkedHashSet,
as described in the Set Interface section.)
• Each key-value pair is called an Entry, hence, Map is
considered as a collection of entry objects.
Map Interface lecture notes by Dr. V Dutta 3
4. Map methods
• Object put(Object key, Object value)
• Void putAll(Map m)
• Object get(Object key)//returns the value associated
with given key.
• Object remove(Object key) // removes the key entry
• Boolean containsKey(Object key)
• Boolean isEmpty(Object key)
• Boolean containsValue(Object key)
• Int size()
• Void clear()
Map Interface lecture notes by Dr. V Dutta 4
5. contd..
• Map contains its own specific methods.
Object put(Object key, Object value)
• e.g to add an entry
– m.put(001, “aaa”); //returns null
– m.put(002, “ccc”); //returns null
– m.put(001, “bbb”); //returns aaa
• If any duplicate value is inserted in values with same key then,
old value is replaced by the new value. Thus the return type is
Object.
Map Interface lecture notes by Dr. V Dutta 5
6. Collection view
The Collection view methods allow a Map to be viewed as
a Collection in these three ways:
• keySet — the Set of keys contained in the Map.
• values — The Collection of values contained in the Map.
This Collection is not a Set, because multiple keys can map to
the same value.
• entrySet — the Set of key-value pairs contained in the Map.
The Map interface provides a small nested interface
called Entry interface (Map.Entry), the type of the elements in
this Set.
– Set keyset()
– Collection values()
– Set entrySet()
Map Interface lecture notes by Dr. V Dutta 6
7. Map
• A map is a group of key value pair and each pair is called an
entry hence map is considered as a collection of entry objects.
Without the existing map object there is no chance of existing
entry object. Hence entry interface is defined inside the Map
interface.
Entry specific methods only applied on entry objects
• Object getKey()
• Object getValue()
• Object setValue(Object newObj)
Map Interface lecture notes by Dr. V Dutta 7
8. Output as a Set view
import java.util.*;
class HashMapDemo
public static void main(String args[])
{ HashMap< String,Integer> hm = new HashMap< String,Integer>();
hm.put("a",new Integer(100));
hm.put("b",new Integer(200));
hm.put("c",new Integer(300));
hm.put("d",new Integer(400));
Set<Map.Entry<String,Integer>> st = hm.entrySet();
for(Map.Entry<String,Integer> me:st)
{ System.out.print(me.getKey()+":");
System.out.println(me.getValue()); } } }
Map Interface lecture notes by Dr. V Dutta 8
9. HashMap
HashMap class is the first implementation of Map. HashMap
class extends AbstractMap and implements Map interface. It
uses a hashtable to store the map. This allows the execution time
of get() and put() to remain same. No insertion order preserved,
based on hashcode of keys. Null is allowed for key( only once)
but any time for values. Hetrogeneous objects are allowed for
both key and value.
Best for search operation. It implements seriealizable and
clonable but not RandomAccess interface.
Map Interface lecture notes by Dr. V Dutta 9
10. Constructors in HashMap
HashMap provides 4 constructors and access modifier of each is public:
• HashMap() : It is the default constructor which creates an instance
of HashMap with initial capacity 16 and load factor 0.75. used as
HashMap hm =new HashMap()
• HashMap(int initial capacity) : It creates an empty HashMap
instance with specified initial capacity and load factor 0.75.
• HashMap hm =new HashMap(int initial capacity)
• HashMap(int initialCapacity, float loadFactor) : It creates a
HashMap instance with specified initial capacity and specified load
factor.
• HashMap(Map m) : It creates instance of HashMap with same
mappings as specified map.
Map Interface lecture notes by Dr. V Dutta 10
11. Methods in HashMap
void clear(): Used to remove all mappings from a map.
boolean containsKey(Object key): Used to return True if for a specified key, mapping is
present in the map.
boolean containsValue(Object value): Used to return true if one or more key is mapped to
a specified value.
Object clone(): It is used to return a shallow copy of the mentioned hash map.
boolean isEmpty(): Used to check whether the map is empty or not. Returns true if the
map is empty.
Set entrySet(): It is used to return a set view of the hash map.
Object get(Object key): It is used to retrieve or fetch the value mapped by a particular key.
Set keySet(): It is used to return a set view of the keys.
int size(): It is used to return the size of a map.
Object put(Object key, Object value): It is used to insert a particular mapping of key-value
pair into a map.
putAll(Map M): It is used to copy all of the elements from one map into another.
Object remove(Object key): It is used to remove the values for any particular key in the
Map.
Collection values(): It is used to return a Collection view of the values in the HashMap.
Map Interface lecture notes by Dr. V Dutta 11
12. Example: Collection view of the Map
import java.util.*;
public class HashMapDemo1{
public static void main(String args[]){
HashMap<Integer,String> hm= new HashMap<Integer,String>();
hm.put(1,"Red");
hm.put(2,"Green");
hm.put(3,"Black");
hm.put(3,null);
hm.put(6,"4");
hm.put(8," ");
hm.put(14,"Black");
hm.put(13,"Black");
hm.put(4,"White");
hm.put(5,"Blue");
System.out.println("Collection view is: "+ hm.values());
System.out.println("Collection view is: "+ hm.keySet());}}
Map Interface lecture notes by Dr. V Dutta 12
13. Synchronized Version
• But we can get synchronized version for ArrayList and
HashMap objects, by using synchronized map method of
collections class. To get synchronized version of HashMap,
• HashMap hm = new HashMap();
• Map hm1 = Collections.synchronizedMap(hm);
// hm1 is synchronized and hm is non-synchronized.
Map Interface lecture notes by Dr. V Dutta 13
14. LinkedHaspMap
• LinkedHashMap is child class of HashMap hence similar
methods and constructors, but LinkedHashMap and HashMap
have similar difference as in LinkedHashSet and in HashSet.
LinkedHashSet and LinkedHashMap are commonly used for
Cache based application
• In LinkedHashMap, the underlying data stucture is LinkedList
and Hashtable while in HashMap it is only Hashtable not
hybrid.
• Insertion order preserved in LinkedHashMap, while in
HashMap not preserved but it is based on hashcode of keys
• LinkedHashMap belongs to 1.4 version. While HashMap is
of 1.2 version.
Map Interface lecture notes by Dr. V Dutta 14
15. import java.util.*;
class DemoMap{
public static void main(String[] args){
LinkedHashMap lhm = new LinkedHashMap(); //replace by HashMap
lhm.put("Monday", 1000);
lhm.put("Saturday", 3000);
lhm.put("Thursday", 4000);
lhm.put("Friday", 2000);
System.out.println(lhm);
System.out.println( lhm.put("Friday", 3000));
Set s =lhm.keySet();
System.out.println(s);
Collection c =lhm.values();
System.out.println(c);
Set s1 =lhm.entrySet();
Iterator itr = s1.iterator();
while(itr.hasNext())
{ @SuppressWarnings("rawtypes")
Map.Entry me = (Map.Entry)itr.next();
System.out.println(me.getKey());
if(me.getKey().equals("Monday"))
{ me.setValue(90000); }}
System.out.println(lhm);}}
Map Interface lecture notes by Dr. V Dutta 15
16. HashMap and Hashtable difference
• HashMap and hashtable have similar difference like arrayList
and Vector.
• Every method in Hashmap is not synchronized, while in
Hashtable is synchronized, ie. At a time multiple thread is
allowed to operate on hashmap, while in hashtable only one
thread is allowed to operate, hence it is thread safe.
• Relatively performance in hashmap is high because thread are
not needed wait time to operate on objects, but in Hashtable
they have to wait.
• Null is allowed for both key and value in hashmap, while in
hashtable not allowed. It gives nullpointerException.
• Hashmap was introduced in 1.2 not legacy, while Hashtable is
legacy(1.0 version)
Map Interface lecture notes by Dr. V Dutta 16
17. Equals and “= =“
• Integer Int1 =new Integer(100);
Integer Int2 =new Integer(100);
System.out.println(Int1= =Int2);//false
System.out.println(Int1.equals(Int2));//true
• Thus it is only different in case of normal hashMap, where
JVM uses .equals() method to identify duplicate keys, which is
meant for content comparison, but in case of IdentityHashMap
JVM uses „==„ operator to identify duplicate keys, it is used
for address comparison.
• Therefore IdentityHashMap has only the only difference of
comparison of objects internally. In HashMap the key is
duplicated hence values are replaced here in example below.
While in Identity it uses === operator .
Map Interface lecture notes by Dr. V Dutta 17
18. Sorted Map
A SortedMap is a Map that maintains its entries in ascending order,
sorted according to the keys' natural ordering, or according to
a Comparator provided at the time of the SortedMap creation. It is the
child interface of Map, It is used when a group of key value pairs are
required to be represented according to some sorted order of keys.
Thus common methods are (similar to SortedSet) :
• Object firstKey();
• Object lastKey();
• SortedMap headMap(Object key);
• SortMap tailMap(Object key)
• SortMap subMap(Object key1, Object key2)
• Comparator comparator()
Map Interface lecture notes by Dr. V Dutta 18
19. TreeMap
• No insertion order(sorting order of keys hashcode)
• Underlying DS is Red Black Tree(balanced)
• No duplicate keys allowed for keys but possible for values
• If dependence is DNSO keys should be homogeneous and
comparable, else get Runtime Exception(ClassCastException).
If customized sorting order using comparator, the keys need
not be homogeneous or comparable. In both sorting case of
orders above there is no restriction for values.
• Null key is possible only for empty TreeMap as first and last
key.(till 1.6 version in 1.7 v it gives NullPointerException)
Map Interface lecture notes by Dr. V Dutta 19
20. TreeMap constructors
Constructors are similar to TreeSet constructors
• TreeMap tr = new TreeMap();// for DNSO
• TreeMap tr = new TreeMap(Comparator c); //CSO
• TreeMap tr = new TreeMap(SortedMap sm);
• TreeMap tr = new TreeMap(Map m);
Map Interface lecture notes by Dr. V Dutta 20
21. Hashtable
• Hashtable was part of original java.util and is a concrete
implementation of a Dictionary. Java Hashtable class is an
implementation of hashtable data structure. It is very much
similar to HashMap in Java, with most significant difference
that Hashtable is synchronized while HashMap is not.
• However, Java 2 re-engineered Hashtable so that it also
implements the Map interface. Thus, Hashtable is now
integrated into the collections framework.
• Like HashMap, Hashtable stores key/value pairs in a hash
table. When using a Hashtable, we specify an object that is
used as a key, and the value that you want linked to that key.
The key is then hashed, and the resulting hash code is used as
the index at which the value is stored within the table.
Map Interface lecture notes by Dr. V Dutta 21
22. Hashtable
• Underlying data structure is Hashtable
• Insertion order based on hash code and not preserved.
• Duplicate keys not allowed, but values can be duplicate
• Heterogeneous objects are allowed for both key and value
• Null is not allowed for both key and value (else it gives
RuntimeException NullPointerException)
• It implements Serializable and Clonable interfaces but not
Random Access
• Every method present in hashtable is Synchronized and hence
hash table object is thread safe.
• It is best choice if frequent operation is search.
Map Interface lecture notes by Dr. V Dutta 22
23. Hashtable Construtors
Similar to HashMap the constructors are:
• Hashtable( )
This is the default constructor of the hash table it instantiates the empty
Hashtable object. (but default size 11, load factor 0.75)
• Hashtable(int size)
This constructor accepts an integer parameter and creates a Hashtable that
has an initial size specified by integer value size.
• Hashtable(int size, float fillRatio)
This creates a Hashtable that has an initial size specified by size and a fill
ratio specified by fillRatio. This ratio must be between 0.0 and 1.0, and it
determines how full the Hashtable can be before it is resized upward.
• Hashtable(Map m)
• This constructs a Hashtable with the given map.
Map Interface lecture notes by Dr. V Dutta 23
24. Code Generating HashCode
class Hcode {
int i;
Hcode(int i){
this.i = i;
}
public String toString(){
return i + " "; // i%7 or any number
}}
hm.put(new Hcode(5), "Pink");
hm.put(new Hcode(7)," ");
hm.put(new Hcode(18),"Black");
hm.put(new Hcode(25),"Black");
hm.put(new Hcode(6),"White");
// hm.put(new Hcode(17),null);
Map Interface lecture notes by Dr. V Dutta 24
25. Properties
• Properties is a subclass of Hashtable. It is used to maintain
lists of values in which the key is a String and the value is also
a String.
• The Properties class is used by many other Java classes. For
example, it is the type of object returned by
System.getProperties( ) when obtaining environmental values.
• Properties define the following instance variable. This variable
holds a default property list associated with a Properties
object.
Map Interface lecture notes by Dr. V Dutta 25
26. Constructors
1 Properties( )
This constructor creates a Properties object
that has no default values.
2 Properties(Properties propDefault)
Creates an object that uses propDefault for
its default values. In both cases, the
property list is empty.
Map Interface lecture notes by Dr. V Dutta 26
27. Sr.No
.
Method & Description
1 String getProperty(String key)
Returns the value associated with the key. A null object is returned if the key is neither in the list
nor in the default property list.
2 String getProperty(String key, String defaultProperty)
Returns the value associated with the key; defaultProperty is returned if the key is neither in the
list nor in the default property list.
3 void list(PrintStream streamOut)
Sends the property list to the output stream linked to streamOut.
4 void list(PrintWriter streamOut)
Sends the property list to the output stream linked to streamOut.
5 void load(InputStream streamIn) throws IOException
Inputs a property list from the input stream linked to streamIn.
6 Enumeration propertyNames( )
Returns an enumeration of the keys. This includes those keys found in the default property list,
too.
7 Object setProperty(String key, String value)
Associates value with the key. Returns the previous value associated with the key, or returns null
if no such association exists.
8 void store(OutputStream streamOut, String description)
After writing the string specified by description, the property list is written to the output stream
linked to streamOut.
Map Interface lecture notes by Dr. V Dutta 27
28. Hashing
• Hashing is designed to solve the problem of needing
to efficiently find or store an item in a collection.
• Hashing means using some function or algorithm to map
object data to some representative integer value. This so-
called hash code (or simply hash) can then be used as a way
to narrow down our search when looking for the item in the
map.
• In java public int hashcode() returns the hash code value.
Map Interface lecture notes by Dr. V Dutta 28