SlideShare a Scribd company logo
1 of 28
Download to read offline
Map Interface
Dr. Vasanti Dutta
Map Interface
Map Interface lecture notes by Dr. V Dutta 2
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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

More Related Content

What's hot

What's hot (20)

Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
Collections and generics
Collections and genericsCollections and generics
Collections and generics
 
07 java collection
07 java collection07 java collection
07 java collection
 
java collections
java collectionsjava collections
java collections
 
An Introduction to Part of C++ STL
An Introduction to Part of C++ STLAn Introduction to Part of C++ STL
An Introduction to Part of C++ STL
 
sets and maps
 sets and maps sets and maps
sets and maps
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
The map interface (the java™ tutorials collections interfaces)
The map interface (the java™ tutorials   collections   interfaces)The map interface (the java™ tutorials   collections   interfaces)
The map interface (the java™ tutorials collections interfaces)
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
Java class 5
Java class 5Java class 5
Java class 5
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
 

Similar to Lecture notesmap

Collection in Java
Collection in JavaCollection in Java
Collection in JavaHome
 
Hash map (java platform se 8 )
Hash map (java platform se 8 )Hash map (java platform se 8 )
Hash map (java platform se 8 )charan kumar
 
Java Presentation
Java PresentationJava Presentation
Java Presentationmdfkhan625
 
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptx
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptxEX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptx
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptxvishal choudhary
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner codeMite Mitreski
 
An important part of electrical engineering is PCB design. One impor.pdf
An important part of electrical engineering is PCB design. One impor.pdfAn important part of electrical engineering is PCB design. One impor.pdf
An important part of electrical engineering is PCB design. One impor.pdfARORACOCKERY2111
 
Google collections api an introduction
Google collections api   an introductionGoogle collections api   an introduction
Google collections api an introductiongosain20
 
Data Structures Design Notes.pdf
Data Structures Design Notes.pdfData Structures Design Notes.pdf
Data Structures Design Notes.pdfAmuthachenthiruK
 
Presentation.pptx
Presentation.pptxPresentation.pptx
Presentation.pptxAgonySingh
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.jstimourian
 
How Hashmap works internally in java
How Hashmap works internally  in javaHow Hashmap works internally  in java
How Hashmap works internally in javaRamakrishna Joshi
 
I need help with this maze gui that I wrote in java, I am trying to .pdf
I need help with this maze gui that I wrote in java, I am trying to .pdfI need help with this maze gui that I wrote in java, I am trying to .pdf
I need help with this maze gui that I wrote in java, I am trying to .pdfarihantgiftgallery
 
JAVA Collections frame work ppt
 JAVA Collections frame work ppt JAVA Collections frame work ppt
JAVA Collections frame work pptRanjith Alappadan
 
Java collections
Java collectionsJava collections
Java collectionsSujit Kumar
 

Similar to Lecture notesmap (20)

Java Collections.pptx
Java Collections.pptxJava Collections.pptx
Java Collections.pptx
 
Collection and framework
Collection and frameworkCollection and framework
Collection and framework
 
Collection in Java
Collection in JavaCollection in Java
Collection in Java
 
Hash map (java platform se 8 )
Hash map (java platform se 8 )Hash map (java platform se 8 )
Hash map (java platform se 8 )
 
Java Presentation
Java PresentationJava Presentation
Java Presentation
 
Java
JavaJava
Java
 
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptx
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptxEX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptx
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptx
 
Java.util
Java.utilJava.util
Java.util
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
 
An important part of electrical engineering is PCB design. One impor.pdf
An important part of electrical engineering is PCB design. One impor.pdfAn important part of electrical engineering is PCB design. One impor.pdf
An important part of electrical engineering is PCB design. One impor.pdf
 
Google collections api an introduction
Google collections api   an introductionGoogle collections api   an introduction
Google collections api an introduction
 
Data Structures Design Notes.pdf
Data Structures Design Notes.pdfData Structures Design Notes.pdf
Data Structures Design Notes.pdf
 
Presentation.pptx
Presentation.pptxPresentation.pptx
Presentation.pptx
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.js
 
How Hashmap works internally in java
How Hashmap works internally  in javaHow Hashmap works internally  in java
How Hashmap works internally in java
 
Hash function
Hash functionHash function
Hash function
 
I need help with this maze gui that I wrote in java, I am trying to .pdf
I need help with this maze gui that I wrote in java, I am trying to .pdfI need help with this maze gui that I wrote in java, I am trying to .pdf
I need help with this maze gui that I wrote in java, I am trying to .pdf
 
Hashing data
Hashing dataHashing data
Hashing data
 
JAVA Collections frame work ppt
 JAVA Collections frame work ppt JAVA Collections frame work ppt
JAVA Collections frame work ppt
 
Java collections
Java collectionsJava collections
Java collections
 

More from Vasanti Dutta

More from Vasanti Dutta (6)

MCA-5 unit1
MCA-5 unit1MCA-5 unit1
MCA-5 unit1
 
Networking lec1 4
Networking lec1 4Networking lec1 4
Networking lec1 4
 
Networking lectures unit 2, MCA VII
Networking lectures unit 2, MCA VIINetworking lectures unit 2, MCA VII
Networking lectures unit 2, MCA VII
 
Networking lecture1
Networking lecture1Networking lecture1
Networking lecture1
 
Jcv course contents
Jcv course contentsJcv course contents
Jcv course contents
 
Servlet classnotes
Servlet classnotesServlet classnotes
Servlet classnotes
 

Recently uploaded

Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 

Recently uploaded (20)

Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 

Lecture notesmap

  • 2. Map Interface Map Interface lecture notes by Dr. V Dutta 2
  • 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