10 Examples of HashMap in Java - Programming Tutorial - Java67
10 Examples of HashMap in Java - Programming Tutorial - Java67
10ExamplesofHashMapinJavaProgrammingTutorial|Java67
Java67
JavaProgrammingtutorialsandInterviewQuestions
Monday,February25,2013
10ExamplesofHashMapinJavaProgrammingTutorial
HashMapinJavaisoneofthemostpopularCollectionclassamongJavaprogrammers.AfterbyarticleHow
HashMapworksinJava,whichdescribestheorypartofJavaHashMap,Ithoughttoshare,Howtouse
HashMapinJavawithfundamentalHashMapexamples,butcouldn'tdothatanditwasslipped.HashMap
isaadatastructure,basedonhashing,whichallowsyoutostoreobjectaskeyvaluepair,advantageof
usingHashMapisthat,youcanretrieveobjectonconstanttimei.e.O(1),ifyouknowthekey.HashMap
implementsMapinterfaceandsupportsGenericsfromJava1.5release,whichmakesittypesafe.There
arecoupleofmoreCollections,whichprovidessimilarfunctionalitieslikeHashMap,whichcanalsobeused
tostorekeyvaluepair.Hashtableisoneofthem,butHashtableissynchronizedandperformspoorinsingle
threadedenvironment.SeeHashtablevsHashMapforcompletedifferencesbetweenthem.Anotherone,
relativelynewisConcurrentHashMap,whichprovidesbetterperformancethanHashtableinconcurrent
environmentandshouldbepreferred.SeedifferencebetweenConcurrentHashMapandHashMapfor
detaildifferences.InthisJavatutorial,wewillseedifferentexamplesofHashMap,likeaddingand
removingentries,iteratingoverJavaHashMap,checkingsizemap,findingifakeyorvalueexistsonMap
andvariousotherexamples,whichweusedfrequently.
JavaHashMapExample
Beforegoingtoseetheseexamples,fewthingstonoteaboutJavaHashMap.Itsnot
synchronized,sodon'tshareyourHashMapamongmultiplethreads.Anothercommoncause
oferrorisclearingMapandreusingit,whichisperfectlyvalidinsinglethreadedenvironment
butifdoneinmultithreadedenvironmentcancreatesubtlebugs.
Laro
Libreng
Online
Games
Maglaro
Onlinesa
Facebook
Kasama1
Bilyon
User.
Libreng
Sumali!
JavaHashMapExample1:CreateandaddobjectsinHashMap
InfirstexampleofHashMap,wewillcreateandaddobjectintoourMap.AlwaysuseGenerics,ifyouare
notworkinginJava1.4.FollowingcodewillcreateHashMapwithkeysoftypeStringandvaluesoftype
Integerwithdefaultsizeandloadfactor.
HashMap<String,Integer>cache=newHashMap<String,Integer>();
alternativelyyoucancreateHashMapfromcopyingdatafromanotherMaporHashtableasshownin
belowexample:
Hashtable<Integer,String>source=newHashtable<Integer,String>();
HashMap<Integer,String>map=newHashMap(source);
Youcanalsosupplyloadfactor(percentageofsize,whichiffulledtriggerresizeofHashMap)and
initialiCapacitywhilecreatinginstancebyusingoverloadedconstructorprovidedinAPI.Addingelements,
alsocalledputoperation,requireskeyandvalueobject.HereisanexampleofaddingkeyandvalueinJava
HashMap:
Followers
Jointhissite
withGoogleFriendConnect
BlogArchive
2015(40)
map.put(21,"TwentyOne");
map.put(21.0,"TwentyOne");//thiswillthrowcompilererrorbecause21.0isn
otinteger
Members(722
2014(68)
2013(49)
December(1)
JavaHashMapExample2:RetrievingvaluefromHashMap
November(3)
AnotherbasicexampleisretrievingvaluefromHashMap.inordertoretrievevalues,weneedtoknowkey
http://java67.blogspot.com/2013/02/10examplesofhashmapinjavaprogrammingtutorial.html
Alreadyamember?
1/6
7/1/2015
10ExamplesofHashMapinJavaProgrammingTutorial|Java67
August(8)
object.let'susethekeyinsertedinlastexample,forgettingvaluebackfromMap.get(key)methodisused
July(6)
togetvalueformHashMap:
June(2)
May(3)
April(2)
Integerkey=21;
Stringvalue=map.get(key);
System.out.println("Key:"+key+"value:"+value);
March(7)
February(7)
Output:Key:21value:TwentyOne
JavaIterator
Example
10Examplesof
HashMapin
Java
Programmin
gTutor...
Difference
betweenJDK
andJREin
Java
Platform
Difference
betweenJIT
andJVMin
Java
Interview...
Canabstract
classhave
Constructor
inJava
Inte...
ClassinJava
andObject
oriented
programmin
glang...
Howto
connect
MySQL
database
fromJava
program
wi...
January(10)
87%
87%
87%
87%
44%
87%
87%
87%
33%
30%
JavaHashMapExample3:IteratingoverHashMap
AnotherwaytogetvaluefromHashMapisbyiteratingoverwholeMap.Sometimewedowanttoloop
throughwholemapandperformoperationsoneachkeyvaluepair,wecanuseIteratorforthatpurpose.In
ordertouseIterator,wefirstneedSetofkeys,whichcanberetrievedusingmap.keySet()method.Bythe
waytherearemultiplewaystoloopthroughMapinJava,seeherefor4waystoloopHashMapinJava.
HereisanexampleofiteratingoverMapusingjava.util.Iterator:
map.put(21,"TwentyOne");
map.put(31,"ThirtyOne");
Iterator<Integer>keySetIterator=map.keySet().iterator();
while(keySetIterator.hasNext()){
Integerkey=keySetIterator.next();
System.out.println("key:"+key+"value:"+map.get(key));
87%
}
Output:
40%
80%
key:21value:TwentyOne
key:31value:ThirtyOne
RecommendedBooksandI
JavaHashMapExample4:SizeandClearinHashMap
TwofundamentalexampleofHashMap,isfindingouthowmanyelementsarestoredinMap,knownas
sizeofMapandclearingHashMaptoreuse.JavaCollectionAPIprovidestwoconvinientmethodcalled
size()andclear()toperformtheseoperationonjava.util.HashMap,hereiscodeexample.
2012(137)
System.out.println("SizeofMap:"+map.size());
map.clear();//clearshashmap,removesallelement
System.out.println("SizeofMap:"+map.size());
Output:
SizeofMap:2
SizeofMap:0
Top10CodingQues
ProgrammingJobIn
GoodJavaInterview
2to3yearsExperie
Programmers
21Frequentlyasked
Questions
20SQLQueryInterv
forJavaDevelopers
18GreatDesignPat
forJavaProgarmers
15JavaEnumbased
Questions
87%
YoucanreuseMapbyclearingit,butbecarefulifitsbeensharedbetweenmultiplethreadswithoutproper
synchronization.Sinceyoumayneedtopreventotherthreadfromaccessingmapwhenitsgettingclear.I
suggestnottodo,untilyouhaveverygoodreasonofdoingit.
87%
40%
1,599
199
87%
57%
JavaHashMapExample5and6:ContainsKeyandContainsValueExample
InthisexampleofJavaHashMap,wewilllearnhowtocheckifMapcontainsaparticularobjectaskeyor
value.java.util.HashMapprovidesconvenientmethodslikecontainsKey(Objectkey)and
http://java67.blogspot.com/2013/02/10examplesofhashmapinjavaprogrammingtutorial.html
2/6
7/1/2015
10ExamplesofHashMapinJavaProgrammingTutorial|Java67
containsValue(Objectvalue)whichcanbeusedtoforcheckingexistenceofanykeyvalueinHashMap.here
87%
87%
87%
44%
87%
87%
87%
87%
87%
87%
iscodeexample:
System.out.println("DoesHashMapcontains21askey:"+map.containsKey(21));
System.out.println("DoesHashMapcontains21asvalue:"+map.containsValue(21
));
System.out.println("DoesHashMapcontainsTwentyOneasvalue:"+map.contains
Value("TwentyOne"));
Output:
DoesHashMapcontains21askey:true
DoesHashMapcontains21asvalue:false
DoesHashMapcontainsTwentyOneasvalue:true
69%
1,400
599
JavaHashMapExample7:CheckingifHashMapisempty
InthisMapexample,wewilllearnhowtocheckifHashMapisemptyinJava.Therearetwowaystofind
87%
87%
outifMapisempty,oneisusingsize()method,ifsizeiszeromeansMapisempty.Anotherwaytocheckif
HashMapisemptyisusingmorereadableisEmpty()methodwhichreturnstrueifMapisempty.Hereis
codeexample:
booleanisEmpty=map.isEmpty();
AdsbyGoogle
System.out.println("IsHashMapisempty:"+isEmpty);
CoreJava
JavaHashmapEx
Output:
JavaProgrammin
IsHashMapisempty:false
JavaHashMapExample8:RemovingObjectsfromHashMap
AnothercommonexampleofJavaHashMapisremovingentriesormappingfromMap.Java.util.HashMap
providesremove(Objectkey)method,whichacceptkeyandremovesmappingforthatkey.Thismethod,
returnsnullorthevalueofentry,justremoved.Hereisacodeexampleofremovingkeyvaluefrom
HashMap:
Integerkey=21;
Objectvalue=map.remove(key);
System.out.println("FollowingvalueisremovedfromMap:"+value);
Output:
FollowingvalueisremovedfromMap:TwentyOne
JavaHashMapExample9:SortingHashMapinJava
HashMapisanunsortedMapinJava,neitherkeyorvalueissorted.IfyouwanttosortHashMapthanyou
cansortitbaseduponkeyorvalue,seehowtosortHashMaponkeysandvaluesforfullcodeexample.
Alternatively,youcanuseSortedMapinJavalikeTreeMap.TreeMaphasconstructorwhichacceptsMap
andcancreateaMapsortedonnaturalorderofkeyoranycustomsortingorderdefinedbyComparator.
OnlythingiskeyshouldbenaturallycomparableandtherecompareTo()methodshouldn'tthrow
exception.JusttoremindthereisnoCollections.sort()methoddefinedforMapisonlyforListandits
implementatione.g.ArrayListorLinkedList.SoanysortingforMaprequireSortedMaporcustomcodefor
sortingoneitherkeyorvalue.hereiscodeexampleofsortingHashMapinJavabyusingTreeMapin
naturalorderofkeys:
http://java67.blogspot.com/2013/02/10examplesofhashmapinjavaprogrammingtutorial.html
3/6
7/1/2015
10ExamplesofHashMapinJavaProgrammingTutorial|Java67
map.put(21,"TwentyOne");
map.put(31,"ThirtyOne");
map.put(41,"ThirtyOne");
System.out.println("UnsortedHashMap:"+map);
TreeMapsortedHashMap=newTreeMap(map);
System.out.println("SortedHashMap:"+sortedHashMap);
Output:
UnsortedHashMap:{21=TwentyOne,41=ThirtyOne,31=ThirtyOne}
SortedHashMap:{21=TwentyOne,31=ThirtyOne,41=ThirtyOne}
JavaHashMapExample10:SynchronizedHashMapinJava
YouneedtosynchronizeHashMapifyouwanttouseitinmultithreadedenvironment.Ifyouarerunning
onJava1.5andaboveconsiderusingConcurrentHashMapinplaceofsynchronizedHashMapbecauseit
providebetterconcurrency.IfyourprojectisstillonJDK1.4thanyougottouseeitherHashtableor
synchronizedMap.Collections.synchronizedMap(map)isusedtosynchronizeHashMapinJava.Seehere
forfullcodeexample.ThismethodreturnsathreadsafeversionofMapandallmapoperationisserialized.
RelatedJavaProgrammingTutorialsfromJava67Blog
1. DifferencebetweenHashMapandArrayListinJava
2. HowtosortArrayListinascendingorderinJava
3. DifferencebetweenTreeMapandTreeSetinJava
4. WhentouseMap,ListandSetcollectioninJava
5. DifferencebetweenHashMapandHashSetinJava
6. DifferencebetweenIdentityHashMapandHashMapinJava
87%
87%
87%
40%
67%
88%
Youmightlike:
JavaCollection
interviewQuestions
Answers|Java
CollectionFAQ
HowtoRead,Write
XLSXFileinJava
ApachPOIExample
Differencebetween
Set,ListandMapin
JavaInterview
question
Differencebetween
Tree
MapandTree
SetinJava
Recommendedby
PostedbyJavinPaulat7:47AM
Labels:corejava,Javacollectiontutorial,JavaprogrammingTutorial
8comments:
May11,2013at12:23PM
Sofar,itisthebestintroarticleonHashMapsI'veeverseen.Pleaseaddsomepracticalexampleof
HashMapusage.
Reply
http://java67.blogspot.com/2013/02/10examplesofhashmapinjavaprogrammingtutorial.html
4/6
7/1/2015
10ExamplesofHashMapinJavaProgrammingTutorial|Java67
Zavier August18,2013at7:36PM
Do you know how to get all key value pair from HashMap using core Java library, without any
externallibrary?Ihavearequirement,whereIneedtoconvertallHashMapkeyvaluestoacolon
separated String e.g. key : value and send them to another system. I don't know how to convert
HashMap to String, as toString() format is not the one I wanted. I have an idea to write a static
method, which takes HashMap and returns a String with all key values pair separted by : and
individualentriessepratedbycomma(,)MyonlyproblemisIdon'tknowhowtogetallkeyvalues
fromMap?
Reply
Replies
Anonymous September3,2013at7:21AM
HiZavier,youcantrythis:
HashMapmap=newHashMap();//oryourhashmapalreadypopulated
for(Entryentry:map.entrySet()){
Stringkey=entry.getKey().toString();
Stringvalue=entry.getValue().toString();
//dowhatyouwantwiththesesstrings
}
Baptiste
Reply
Anonymous March19,2014at9:08AM
Veryniceexamples,thanks!
Justonequestion,ifwehavethepair(21,"TwentyOne")andwewanttochangeitto(21,"Twenty
Two")willthe
map.put(21,"TwentyTwo");commandwork?
Reply
Replies
Anonymous March26,2014at3:45AM
Ok,Ireadinjavadocs,itwill.
Reply
Anonymous July16,2014at1:35AM
Nicetutomate.MuchHelp
Reply
Anonymous September16,2014at12:08AM
goodtutorial
Reply
Anonymous June29,2015at1:59AM
Ineverseenthistypeoftutorial.goodtutorial
Reply
http://java67.blogspot.com/2013/02/10examplesofhashmapinjavaprogrammingtutorial.html
5/6
7/1/2015
10ExamplesofHashMapinJavaProgrammingTutorial|Java67
Enteryourcomment...
Commentas:
Publish
GoogleAccount
Preview
NewerPost
Home
OlderPost
Subscribeto:PostComments(Atom)
PoweredbyBlogger.
http://java67.blogspot.com/2013/02/10examplesofhashmapinjavaprogrammingtutorial.html
6/6